gpt4 book ai didi

java - 覆盖Java中的默认构造函数

转载 作者:搜寻专家 更新时间:2023-11-01 04:03:14 25 4
gpt4 key购买 nike

非常简单的问题,但无论如何:是否有任何理由像这样覆盖默认构造函数:

public SomeObject(){
}

这是公开的。它没有任何逻辑。那么,有必要吗?我没看到全貌?

感谢您的所有帮助。

最佳答案

定义一个空的无参数构造函数的一个原因是如果还有一个非默认构造函数并且仍然希望无参数构造函数可访问(公共(public)或 protected )。

这是因为任何 [other] 构造函数定义 will prevent the automatic addition默认的无参数构造函数:

The compiler automatically provides a [public] no-argument, default constructor for any class without constructors.

(也请参阅该链接中的下一部分,其中讨论将被调用的默认 super 构造函数。)

即使从未手动使用无参数构造函数,它对于其他事情也可能很重要,例如Serializable :

During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream.

关于java - 覆盖Java中的默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11849942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com