Overriding static method in java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Overriding static method in java

By the definition of hiding, the method in the subclass is hiding the one in the superclass. I don't see how the subclass is "covering up/hiding" the superclass static method, as the superclass's method is the one that's actually called https://code.sololearn.com/c86JJRjpXI3c/?ref=app

15th Jun 2018, 12:13 AM
harshit - avatar
2 Answers
+ 2
Static methods can not be overriding, what you observe is known as hiding the static method. A method of the same class as the variable will be called.
15th Jun 2018, 5:47 AM
Medvedev Artem
Medvedev Artem - avatar
Static methods are usually invoked by "ClassName.staticMethod()" since they are tied to the class itself and not too a specific instance of the class. Though possible to invoke them with "classObject.staticMethod()" as you did, this is not recommended. Your code is a perefect example of why this second form is a bad idea. The compiler uses the declared class type of the variable to determine which static method to call. So even though the variable is storing an object of the subclass B, the variable is declared as type class A and so A.show() is the static method called. Since this is contrary to normal override behavior, most compilers will generate a warning to let you know output may be different than expected.
16th Jun 2018, 4:20 AM
Shardis Wolfe