有关java中static关键的重写问题

《Java编程思想》中这样提到“只有普通的方法调用可以是多态的”。说白了,就是静态方法不能实现重写这种多态。

JAVA静态方法形式上可以重写(只要子类不加@Override关键字修饰的话,即可编译通过),但从本质上来说不是JAVA的重写。因为静态方法只与类相关,不与具体实现相关,声明的是什么类,则引用相应类的静态方法(本来静态无需声明,可以直接引用),看下例子:

Java代码
  1. class Base{ 
  2.         static void a( ){System.out.println("A");  } 
  3.                  void b( ){System.out.println("B"); } 
  4. public class  Inherit extends Base{ 
  5.           static void a( ){System.out.println("C");  } 
  6.                   void b( ){System.out.println("D"); } 
  7.            public static void main(String args[]){ 
  8.                     Base b=new Base(); 
  9.                     Base  c=new Inherit(); 
  10.                     b.a(); 
  11.                     b.b(); 
  12.                     c.a(); 
  13.                     c.b(); 
  14.          } 
class Base{
        static void a( ){System.out.println("A");  }
                 void b( ){System.out.println("B"); }
}
public class  Inherit extends Base{
          static void a( ){System.out.println("C");  }
                  void b( ){System.out.println("D"); }
           public static void main(String args[]){
                    Base b=new Base();
                    Base  c=new Inherit();
                    b.a();
                    b.b();
                    c.a();
                    c.b();
         }
}

以上输出的结果是:A                            B                            A                            D 非静态方法 按重写规则调用相应的类实现方法,而静态方法只与类相关。

原文地址:https://www.cnblogs.com/xiohao/p/4233561.html