考虑以下:
public class parent {
int x;
parent() {
x = 5;
}
}
public class child extends parent {
int y;
child() {
super();
y = 10;
}
public static void main(String[] args) {
parent p = new child();
System.out.println(p.y);//can't access variable y
}
Run Code Online (Sandbox Code Playgroud)
}
这里,在父类的对象上调用子类的构造函数.在进行Android编程时,我多次遇到过这种情况.我的问题是为什么允许这样做?子类的构造函数可能初始化其他成员,但是他们的蓝图可能没有像上面的情况那样在父类中定义.