问题描述
很容易的问题,但无论如何:有任何理由重写默认构造函数像这样:
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:
,其中它谈到将被调用的默认超级构造函数。)
(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:
这篇关于覆盖Java中的默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!