class A{
    public static void testP(){
       System.out.println("A");
       }
    public void testM(){
       System.out.println("X");
       }
}class B extends A{
    public static void testP(){
       System.out.println("B");
       }
    public void testM(){
       System.out.println("Y");
       }
}public class Test1{
    public static void main(String[] args){
       A a=new A();
       B b=new B();
       a.testP();//结果是 A
       b.testP();//结果是 B
       a.testM();//结果是 X
       b.testM();//结果是 Y
       a=b;
       a.testP();//结果是  A
       b.testP();//结果是  B
       a.testM();//结果是  Y
       b.testM();//结果是  Y
  
       }
}
既然a=b,为什么a.testP()和b.testP()的结果不一样?

解决方案 »

  1.   

    a.testP() 等价于 a.getClass().testP(),即A.testP()
    b.testP() 等价于 b.getClass().testP(),即B.testP()
      

  2.   

    不一样的原因是,静态方法不能被重写,详情见:
    http://topic.csdn.net/u/20090203/10/3b55ea03-c388-48f7-8574-578b25b07e58.html
      

  3.   

    a=b是时只是把 变量b所指向的地址值赋给a,类静态属性和对象不在一个存储空间内
      

  4.   

    应该可以用下面静态绑定和动态绑定来理解:a.testP(); //因为A里面的testP()是static,编译时就静态绑定了,所以输出 A.testP()a.testM(); //而testM()不是static方法,a是由B new出来的,执行的时候会执行new它的那个类的testM()方法,所以输出B.method2(),这是java的多态性
      

  5.   

    a和b都是引用类型.a=b只是把b指向的地址给了a,但是a还是一个A类型的...我不明白的是,静态方法能否被对象调用?
    比如A为静态方法,a.testP合法不?