在Java程序中,我有多个继承自父类的子类(它是抽象的).我想表达的是,每个孩子都应该有一个只设置一次的成员(我打算从构造函数中做到这一点).我的计划是编码s.th. 像这样:
public abstract class Parent {
protected final String birthmark;
}
public class Child extends Parent {
public Child(String s) {
this.birthmark = s;
}
}
Run Code Online (Sandbox Code Playgroud)
然而,这似乎不能取悦Java神.在父类中,我收到birthmark"可能尚未初始化" 的消息,在子类中我得到" birthmark无法访问最终字段".
那么Java的方式是什么呢?我错过了什么?
Ada*_*eld 19
你不能这样做,因为在比较父类时,编译器不能确定子类是否会初始化它.你必须在父的构造函数中初始化它,并让子调用父的构造函数:
public abstract class Parent {
protected final String birthmark;
protected Parent(String s) {
birthmark = s;
}
}
public class Child extends Parent {
public Child(String s) {
super(s);
...
}
}
Run Code Online (Sandbox Code Playgroud)
将它传递给父构造函数:
public abstract class Parent {
private final String birthmark;
public Parent(String s) {
birthmark = s;
}
}
public class Child extends Parent {
public Child(String s) {
super(s);
}
}
Run Code Online (Sandbox Code Playgroud)