package test;
public class test {
private String baseName = "base";
public test() {
callName();
}
public void callName() {
System.out.println(baseName);
}
static class Sub extends test {
private String baseName = "sub";
public void callName() {
System.out.println(baseName);
}
}
public static void main(String[] args) {
test bb = new Sub();
}
}
为什么输出结果为 null?
父类先初始化,并且父类构造函数调用了callName()方法,子类会覆盖这个方法,但是子类这时候还没初始化,所以只能打印默认值(null)
你好,如果把代码改成
package test;
public class test {
private String baseName = "base";
public test() {
callName();
}
public void callName() {
System.out.println(11);
}
static class Sub extends test {
private String baseName = "sub";
public void callName() {
System.out.println(22);
}
}
public static void main(String[] args) {
test bb = new Sub();
}
}
按照你的解释还是输出null,但是输出22,好像不是这个原因