[英]Making sure a final field is initialized in Java
I extend a class with multiple constructors. 我用多个构造函数扩展了一个类。 I add a final field in my subclass which ofcourse needs to be initialized in my own constructors.
我在子类中添加了一个final字段,这当然需要在自己的构造函数中进行初始化。
The problem is I don't want to re-implement (most) of the constructors of the superclass, so I would like to do something like this: 问题是我不想重新实现(大多数)超类的构造函数,所以我想做这样的事情:
public myConstructor(Object... params){
super(params);
try{
this.finalField = "backup value";
}
catch(someException e){
}
}
Is this possible in some way or the other? 这有可能以其他方式出现吗?
edit : I realized this scenario will never happen, because the superclass constructor will never call my own constructor. 编辑 :我意识到这种情况永远不会发生,因为超类构造函数永远不会调用我自己的构造函数。
To simplify process of object initialization, usually I use the following solutions: 为了简化对象初始化的过程,通常我使用以下解决方案:
让所有构造函数都调用一个用于设置final字段的构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.