日期:2014-05-20  浏览次数:20642 次

一段JAVA代码,不太明白其中的含义,请大家帮帮忙
public   class   ploytest  
{  

public   static   void   main(String[]   args)  
{  
A   a   =   new   A();  
B   b   =   new   B();  
a.s   =   "[AA] ";  
System.out.println(a.s);
b.s   =   "[BB] ";  
a   =   b;  
System.out.println(a.s);  

System.out.println(b.s);  

System.out.println(a.getS());  

System.out.println(b.getS());  

System.out.println( "==================== ");  
((A)b).s   =   "[AA] ";  
System.out.println(a.s);  

System.out.println(b.s);  
System.out.println(a.getS());  
System.out.println(b.getS());  

}  
}  

class   A  
{  
String   s   =   "[A] ";  
String   getS()  
{  
return   s;  
}  
}  

class   B   extends   A
{  
String   s   =   " ";  
String   getS()  
{  
return   s;  
}  
}  

我看到的输出结果如下:
[AA]
[A]
[BB]
[BB]
[BB]
====================
[AA]
[BB]
[BB]
[BB]
具体是怎么执行的呢?有哪位大哥可以给讲解一下不?

------解决方案--------------------
A a = new A(); //a.s= "[a] "
B b = new B(); //b是继承的,父类s= "[a] ",子类s= " "
a.s = "[AA] "; //a.s= "[aa] "
System.out.println(a.s);
b.s = "[BB] "; //b子类s= "[bb] "
a = b; //a指向b的对象
System.out.println(a.s); //a.s就是b的父类s= "[a] "

System.out.println(b.s); //b的子类s= "[bb] "

System.out.println(a.getS()); //调用的是子类getS,返回子类s= "[bb] "

System.out.println(b.getS()); //调用子类getS,返回子类s= "[bb] "

System.out.println( "==================== ");
((A)b).s = "[AA] "; //b的父类s= "[aa] "
System.out.println(a.s); //b父类s

System.out.println(b.s); //b子类s
System.out.println(a.getS()); //调用子类getS,返回子类s= "[bb] "
System.out.println(b.getS()); //调用子类getS,返回子类s= "[bb] "