-2
class B extends A {
    static public void printMe(){
        System.out.println("in static B");
    }
}
class A{
    static public void printMe(){
        System.out.println("In static A");
    }
}

public static void main(String[] args) {
        A a = new B();
        a.printMe();
    }

Why is the output "In static A" ?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
robin
  • 1,893
  • 1
  • 18
  • 38
  • 4
    There is no "Static method overriding in Java" – Eran Jan 10 '18 at 10:29
  • @Eran if you have issue with the title I changed it. – robin Jan 10 '18 at 10:31
  • Consequence: don't use static: use a singleton if you need only one instance (of course the singleton implementation may use static inside) – pdem Jan 10 '18 at 10:31
  • Related / duplicate: [Is it possible to override a static method in derived class?](https://stackoverflow.com/q/2831426) – Bernhard Barker Jan 10 '18 at 10:33
  • There is a reason why you should never call a static method on an "object instance" - you should just say `A.printMe()` or `B.printMe()`. I consider Java allowing to call static methods on an instance an error in the language specs... – Gyro Gearless Jan 10 '18 at 10:34
  • I have no issue with the title. I just stated that there's no such thing in Java, which is why you see the described behavior. – Eran Jan 10 '18 at 10:34

2 Answers2

4

Static members bind to type rather than implemented type. Hence you see the methods executing from class A.

And static members are not to be ovverriden and they share same copy regardless of instance state.

If you need methods to be ovveriden, do not use them as static members.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • "static members are not to be overridden". They can't be overridden. They can be 'hidden' by a new static implementation in the child class, though. – Stultuske Jan 10 '18 at 10:37
  • True. Stressing only about overriding. – Suresh Atta Jan 10 '18 at 10:38
  • I understand, but sometimes people assume that if you can put a static method with the same signature in a child class, it means it has been overridden. Causes quite a lot of mistakes – Stultuske Jan 10 '18 at 11:12
0

Static member or method belongs to class level instead of specific instance.

A static class will have only 1 instance even if you create multiple instance or do not create instance.

In your case, since you have created instance of class A, method inside class A is implemented.

Another way to get a clear concise for the problem scenario is try running the code mentioned below:

public static void main(String[] args) {
A.printMe();
}

You will get clear idea.