MartinDenny2069
MartinDenny2069

Reputation: 153

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 {
  public static void foo() {
      System.out.println("I am child class");
  }
}

Upvotes: 13

Views: 23024

Answers (6)

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..

Upvotes: 0

Artefacto
Artefacto

Reputation: 97835

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

Upvotes: 19

Phani
Phani

Reputation: 5427

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();

Upvotes: 0

Ukko
Ukko

Reputation: 2266

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.

Upvotes: 1

Chris Ballance
Chris Ballance

Reputation: 34347

In Java, static method lookups are determined at compile time and cannot adapt to subclasses which are loaded after compilation.

Upvotes: 4

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181290

No. It's not possible.

Some similar (not the same) questions here and here.

Upvotes: 0

Related Questions