最终变量和构造函数重载
Final variable and Constructor Overloading
我想在我的 class 中使用 构造函数重载 并且我还想要一些 final 变量来定义.
我想要的结构是这样的:
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;
}
}
我想调用 this() 以避免重写我的第一个构造函数中的代码,但我已经定义了最终变量,所以这会产生编译错误。
我想到的最方便的解决方案是避免使用 final 关键字,但这当然是最糟糕的解决方案。
在多个构造函数中定义变量并避免代码重复的最佳方法是什么?
你快到了。重写构造函数,使默认构造函数调用值为 0 的重载构造函数。
public class MyClass {
private final int variable;
public MyClass() {
this(0);
}
public MyClass(int value) {
variable = value;
}
}
如果你有小数字变量那么使用伸缩构造函数模式是可以的。
我的课() { ... }
MyClass(int value1) { ... }
披萨(int value1,int value2,int value3){ ... }
If there is multiple variable and instead of using method overloading you can use builder pattern so you can make all variable final and will build object gradually.
public class Employee {
private final int id;
private final String name;
private Employee(String name) {
super();
this.id = generateId();
this.name = name;
}
private int generateId() {
// Generate an id with some mechanism
int id = 0;
return id;
}
static public class Builder {
private int id;
private String name;
public Builder() {
}
public Builder name(String name) {
this.name = name;
return this;
}
public Employee build() {
Employee emp = new Employee(name);
return emp;
}
}
}
您不能在两个构造函数中分配 final
变量。如果您想保留 final
变量并且还想通过构造函数进行设置,那么您可以使用一个构造函数来设置最终变量,并且还包括 class 所需的通用代码功能。然后从另一个构造函数调用它,例如 this(*finalVariableValue*);
我想在我的 class 中使用 构造函数重载 并且我还想要一些 final 变量来定义.
我想要的结构是这样的:
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;
}
}
我想调用 this() 以避免重写我的第一个构造函数中的代码,但我已经定义了最终变量,所以这会产生编译错误。 我想到的最方便的解决方案是避免使用 final 关键字,但这当然是最糟糕的解决方案。
在多个构造函数中定义变量并避免代码重复的最佳方法是什么?
你快到了。重写构造函数,使默认构造函数调用值为 0 的重载构造函数。
public class MyClass {
private final int variable;
public MyClass() {
this(0);
}
public MyClass(int value) {
variable = value;
}
}
如果你有小数字变量那么使用伸缩构造函数模式是可以的。
我的课() { ... }
MyClass(int value1) { ... }
披萨(int value1,int value2,int value3){ ... }
If there is multiple variable and instead of using method overloading you can use builder pattern so you can make all variable final and will build object gradually.
public class Employee {
private final int id;
private final String name;
private Employee(String name) {
super();
this.id = generateId();
this.name = name;
}
private int generateId() {
// Generate an id with some mechanism
int id = 0;
return id;
}
static public class Builder {
private int id;
private String name;
public Builder() {
}
public Builder name(String name) {
this.name = name;
return this;
}
public Employee build() {
Employee emp = new Employee(name);
return emp;
}
}
}
您不能在两个构造函数中分配 final
变量。如果您想保留 final
变量并且还想通过构造函数进行设置,那么您可以使用一个构造函数来设置最终变量,并且还包括 class 所需的通用代码功能。然后从另一个构造函数调用它,例如 this(*finalVariableValue*);