tags:

views:

199

answers:

6

I have a static method defined in a base class, I want to overwrite 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");
  }
}
A: 

No. It's not possible.

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

Pablo Santa Cruz
+7  A: 

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
Artefacto
You mean overriding, not overloading. Overloading is when you have two methods of the same name with different signatures.
Joel
You're right, I fixed the post. Thanks.
Artefacto
I changed my mind and wrote "no dynamic dispatch", since that's the general concept involved.
Artefacto
Uh, you don't use callMe() at all...
RCIX
The correct terms are "superclass" and "subclass", not "base class" and "child class".
Jesper
I'd just copy-pasted MartinDenny2069's question. I changed the post to reflect your suggestions.
Artefacto
+4  A: 

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

Chris Ballance
+1  A: 

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.

Ukko
A: 

i am coming to learn it

嘿嘿 ,这个论坛貌似不错哦,嘿嘿
A: 

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