public class A extends B {
public int a = 100;
public A() {
super();
System.out.println(a);
a = 200;
}
static {
System.out.println("static A");
}
public static void main(String[] args) {
new A();
}
}
class B {
public B() {
System.out.println(((A) this).a);
}
}
输出结果是
....... static A
0
100
B的构造方法为啥输出的是0呢?感觉((A) this).a这里挺乱,求大神分析
另外一点就是 B类的构造函数这一个地方,这样直接转为子类不会出现ClassCastException异常吗。
对于父类转为子类的,不许是父类变量指向子类对象,这样转为子类安全合法吧。
Person p1 = new Student(); 让一个Person引用指向Student对象。
Student stu1 = (Student)p1; //ok:将p转换为原类型。
Person p2 = new Employee();
Student stu2 = (Student)p2; //error: 试图将一个Employee强转为一个Student,会抛ClassCastException(类型转换异常)
Person p3 = new Person();
Student stu3 = (Student)p3; //error: 试图将父类转为子类,抛ClassCastException