我想在我的类中使用构造函数重载,我还想定义一些最终变量。
我想要的结构是这样的:
public class MyClass{
private final int variable;
public MyClass(){
/* some code and
other final variable declaration */
variable = 0;
}
public MyClass(int value){
this();
variable = value;
}
}
Run Code Online (Sandbox Code Playgroud)
我想调用this()以避免在我的第一个构造函数中重写代码,但我已经定义了最终变量,因此这会产生编译错误。我想到的最方便的解决方案是避免使用 final 关键字,但这当然是最糟糕的解决方案。
在多个构造函数中定义变量并避免代码重复的最佳方法是什么?