覆盖Java中的默认构造函数 [英] Overriding default constructor in Java
问题描述
很容易的问题,但无论如何:有任何理由重写默认构造函数像这样:
Pretty easy question, but anyway: is there any reason to override default constructor like this:
public SomeObject(){
}
这是公开的。它没有任何逻辑。那么,有必要吗?我没有看到整张图片。
It is public. It is does not have any logic. So, is there necessary? I didn't see the whole picture?
感谢您的帮助。
推荐答案
定义空的无参构造函数的一个原因是如果还有也是一个非默认构造函数,并且仍然希望无参构造函数可访问(public或protected)。
One reason to define an empty no-arg constructor is if there is also a non-default constructor and the no-arg constructor is still desired to be accessible (public or protected).
这是因为任何[其他]构造函数定义将防止自动添加默认无参构造函数:
This is because any [other] constructor definition will prevent the automatic addition of the default no-arg constructor:
编译器自动为没有构造函数的任何类提供了一个[public]无参的默认构造函数。
The compiler automatically provides a [public] no-argument, default constructor for any class without constructors.
,其中它谈到将被调用的默认超级构造函数。)
(See the next bit in that link as well, where it talks about the default super constructor that will be called.)
即使no-arg构造函数从未被手动使用,它对其他事情也很重要,例如可序列化:
Even if the no-arg constructor is never used manually, it can be important for other things, e.g. Serializable:
在反序列化期间,非可序列化类的字段将使用类的public或protected非arg构造函数初始化。 可序列化子类的字段将从流中恢复。
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中的默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!