public class Test27{
public static void main(String[] args){
B b1,b2 = new B();
A a1,a2;
a1=(A)b2;
a2=b2;
System.out.println(a1.s);
a1.show();
System.out.println(a2.s);
a2.show();
b1=(B)a1;
System.out.println(b1.s);
b1.show();
System.out.println(b2.s);
b2.show();
}
}
class A{
String s ="class A";
void show(){
System.out.println(s);
}
}
class B extends A{
String s ="class B";
void show(){
System.out.println(s);
}
}
谁能帮我解释解释这个程序的结果,为什么?
------解决方案--------------------------------------------------------
- Java code
public class Test27{public static void main(String[] args){B b1,b2 = new B();A a1,a2;a1=(A)b2;a2=b2;System.out.println(a1.s); //a1 是A对象,所以a1.s --> class Aa1.show(); //因为b2是B的实例,所以 a1.show() -->调用的是B的show(),B的s会把A的s覆盖掉,所以 class BSystem.out.println(a2.s);//a1 是A对象,所以a1.s --> class Aa2.show();//因为b2是B的实例,所以 a1.show() -->调用的是B的show(),B的s会把A的s覆盖掉,所以 class Bb1=(B)a1;System.out.println(b1.s);//b1 是B对象,所以b1.s --> class Bb1.show();//因为b1=(B)a1 ,a1本来赋值是B的实例,所以 b1.show() -->调用的是B的show(),所以 class BSystem.out.println(b2.s); // class Bb2.show(); // class B}}class A{String s ="class A";void show(){System.out.println(s);}}class B extends A{String s ="class B";void show(){System.out.println(s);}}