请考虑以下内容:
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
}
在父类对象中调用了子类的构造函数。在进行Android编程时,我经常遇到这种情况。
我的问题是为什么允许这样做?子类的构造函数可能会初始化其他成员,但是像上面的例子中一样,它们的蓝图可能没有在父类中定义。
child extends parent
),它意味着子类拥有父类所有的东西,再加上一些自己的字段和方法。 - launeParent
而不是parent
,以及Child
而不是child
。您不必在自己的代码中遵循惯例,但是遵循惯例非常有用,并且在与他人共享代码时遵循惯例非常有用(例如在此处提问时)。 :-) - T.J. Crowder