那么为什么我可以像孩子一样建立父类而不是相反呢?
当我将父类的对象设置为子类,反之亦然,不会复制属性的原因?
public class senior {
private int a = 6;
public int getA() {
return a;
}
public int x = 1;
}
class junior extends senior {
public junior() {
super();
}
public int x = 0;
}
public class runner {
public static void main(String[] args) {
senior S = new senior();
junior J = new junior();
senior S1 = new senior();
junior J1 = new junior();
int b = J.getA();
System.out.println(b);
S = J; // aliasing ?
// J 0 S 1
System.out.println(S.x); // should print 0 but prints 1
System.out.println(J.x);
J1 = (junior) S1; // Senior cannot be cast to junior, why?
System.out.println(S1.x);
System.out.println(J1.x);// should print 1 but prints 0
}
}
答案 0 :(得分:2)
Child类继承其所有父类的所有方法和属性。但另一种方式不正确,因为子类是扩展基类的类,而基类不扩展子类。希望它有所帮助。
答案 1 :(得分:1)
S = J; //aliasing ?
那只是分配。
//J 0 S 1
System.out.println (S.x); // should print 0 but prints 1
变量绑定到类型。虽然底层对象是j,但类型是S(左侧)
J1 = (junior)S1; //Senior cannot be cast to junior, why?
每个卡车司机都是司机,但你不能说每个司机都是卡车司机。
System.out.println (S1.x);
System.out.println (J1.x);// should print 1 but prints 0
变量绑定到类型。对象类型是j。变量指的是J.如果你想使用超级变量试试super.x