Is it possible to override a static method in derived class?

后端 未结 7 1777
暗喜
暗喜 2020-11-28 13:33

I have a static method defined in a base class, I want to override this method in its child class, is it possible?

I tried this but it did not work as I expected. Wh

7条回答
  •  清酒与你
    2020-11-28 14:34

    Static method calls are resolved on compile time (no dynamic dispatch).

    class main {
        public static void main(String args[]) {
                A a = new B();
                B b = new B();
                a.foo();
                b.foo();
                a.callMe();
                b.callMe();
        }
    }
    abstract class A {
        public static void foo() {
            System.out.println("I am superclass");
        }
    
        public void callMe() {
            foo(); //no late binding here; always calls A.foo()
        }
    }
    
    class B extends A {
        public static void foo() {
            System.out.println("I am subclass");
        }
    }
    

    gives

    I am superclass
    I am subclass
    I am superclass
    I am superclass
    

提交回复
热议问题