Why is the static method of the parent class called when the subclass has already overridden it?

I am confused by the behavior of a static method when it is overridden in a subclass.

Below is the code:

public class SuperClass { public static void staticMethod() { System.out.println("SuperClass: inside staticMethod"); } } public class SubClass extends SuperClass { //overriding the static method public static void staticMethod() { System.out.println("SubClass: inside staticMethod"); } } public class CheckClass { public static void main(String[] args) { SuperClass superClassWithSuperCons = new SuperClass(); SuperClass superClassWithSubCons = new SubClass(); SubClass subClassWithSubCons = new SubClass(); superClassWithSuperCons.staticMethod(); superClassWithSubCons.staticMethod(); subClassWithSubCons.staticMethod(); } } Below is the output which we are getting : 1) SuperClass: inside staticMethod 2) SuperClass: inside staticMethod 3) SubClass: inside staticMethod 

Why is the static superclass method called here in the second case?

If the method is not static, then according to polymorphism, the subclass method is called when the subclass object is passed at run time.

+4
source share
4 answers

The static resolution of a method is always based on the Reference type.
The code

 superClassWithSuperCons.staticMethod(); superClassWithSubCons.staticMethod(); subClassWithSubCons.staticMethod(); 

converted to this after compilation

 SuperClass.staticMethod(); SuperClass.staticMethod(); SubClass.staticMethod(); 

By connecting to this, this is a call to the SuperClass method, not a subclass method. So, you get the output of the SuperClass method.

+6
source

A declared static method cannot be overridden, but can be re-declared. This is the answer. The static method is not associated with any instance of the class, so the concept is not applicable. Try the same with non-static and you will see the difference.

Your question is actually duplicated: Why does Java not allow overriding static methods?

+4
source

Interest Ask. I am not familiar with the basic mechanisms, but it seems that for static methods to solve the method call, the declared type is considered (in your average SuperClass example), and not the actual SubClass type. It really makes sense because you are not looking at the actual instance of the object when calling a static function.

+3
source

Static methods are redefined, not redefined ...

If you try to override a static method, then it will be considered as a non-redefined method of the subclass.

Static methods will be called based on the type of reference, not the object.

For more information, visit the page. http://javaunturnedtopics.blogspot.in/2016/07/static-methods-are-redefined-not.html

0
source

Source: https://habr.com/ru/post/1502193/


All Articles