Is it possible to override a static method in derived class?
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. When I created an instance of class B and invoke its callMe() method, the static foo() method in class A is invoked.
public abstract class A {
public static void foo() {
System.out.println("I am base class");
}
public void callMe() {
foo();
}
}
Public class B {
publ开发者_运维百科ic static void foo() {
System.out.println("I am child class");
}
}
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
In Java, static method lookups are determined at compile time and cannot adapt to subclasses which are loaded after compilation.
Just to add a why to this. Normally when you call a method the object the method belongs to is used to find the appropriate implementation. You get the ability to override a method by having an object provide it's own method instead of using the one provided by the parent.
In the case of static methods there is no object to use to tell you which implementation to use. That means that the compiler can only use the declared type to pick the implementation of the method to call.
No. It's not possible.
Some similar (not the same) questions here and here.
Static Methods are resolved at compile time.So if you would like to call parent class method then you should explicitly call with className or instance as below.
A.foo();
or
A a = new A();
a.foo();
In a nutshell static method overriding is not polymorphism it is "method hiding". When you override a static method you will have no access to the base class method as it will be hidden by the derived class.. Usage of super() will throw a compile time error..
精彩评论