创建一个由 child class 初始化的最终字段
Create a final field initialized by a child class
我有一个抽象 class 和 subclasses 共享一个方法,该方法按特定增量递增一个值,并受下限和上限限制。每个subclass都有自己的increment和自己的bounds 这些值应该都声明为final,但是如果我声明它们为final,它们怎么能被subclasses.
初始化
下面是我能想到的唯一方法,但看起来很麻烦。
public abstract class ClassA {
protected int LOWER_LIMIT;
protected int UPPER_LIMIT;
protected int INCREMENT;
public ClassA() {
}
}
public class ClassB extends ClassA {
public ClassB() {
super();
this.LOWER_LIMIT = 0;
this.UPPER_LIMIT = 4200;
this.INCREMENT = 15;
}
}
public class ClassC extends ClassA {
public ClassC() {
super();
this.LOWER_LIMIT = 0;
this.UPPER_LIMIT = 99;
this.INCREMENT = 1;
}
}
最常见的模式是这样的。您还强制子类定义值。
public abstract class Base {
final protected int field1;
final protected int field2;
final protected int field3;
protected Base(int field1, int field2, int field3) {
this.field1 = field1;
this.field2 = field2;
this.field3 = field3;
}
}
public class Subclass extends Base {
public Subclass () {
super(0, 4200, 15);
}
}
我有一个抽象 class 和 subclasses 共享一个方法,该方法按特定增量递增一个值,并受下限和上限限制。每个subclass都有自己的increment和自己的bounds 这些值应该都声明为final,但是如果我声明它们为final,它们怎么能被subclasses.
初始化下面是我能想到的唯一方法,但看起来很麻烦。
public abstract class ClassA {
protected int LOWER_LIMIT;
protected int UPPER_LIMIT;
protected int INCREMENT;
public ClassA() {
}
}
public class ClassB extends ClassA {
public ClassB() {
super();
this.LOWER_LIMIT = 0;
this.UPPER_LIMIT = 4200;
this.INCREMENT = 15;
}
}
public class ClassC extends ClassA {
public ClassC() {
super();
this.LOWER_LIMIT = 0;
this.UPPER_LIMIT = 99;
this.INCREMENT = 1;
}
}
最常见的模式是这样的。您还强制子类定义值。
public abstract class Base {
final protected int field1;
final protected int field2;
final protected int field3;
protected Base(int field1, int field2, int field3) {
this.field1 = field1;
this.field2 = field2;
this.field3 = field3;
}
}
public class Subclass extends Base {
public Subclass () {
super(0, 4200, 15);
}
}