-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" ?

6
  • 4
    There is no "Static method overriding in Java" Commented Jan 10, 2018 at 10:29
  • @Eran if you have issue with the title I changed it. Commented Jan 10, 2018 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) Commented Jan 10, 2018 at 10:31
  • Related / duplicate: Is it possible to override a static method in derived class? Commented Jan 10, 2018 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... Commented Jan 10, 2018 at 10:34

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

"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.
True. Stressing only about overriding.
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
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.

1 Comment

the point is: the instance is of B, it's the declaration that limits it to an A.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.