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

邮差的信 提交于 2019-12-01 18:41:39

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

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

is converted to this after compilation

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

Accroding to this it is the call to SuperClass method not the subclass method.So you are getting the output of SuperClass method.

Ivan Voroshilin

A method declared static cannot be overridden but can be re-declared. That's the answer. A static method is not associated with any instance of a class so the concept is not applicable. Try the same with not static and you'll see the difference.

Your question is duplicated actually: Why doesn't Java allow overriding of static methods?

Interesting question. I'm not familiar with the underlying mechanisms, but it seems that for static methods, the declared type (in your middle example, SuperClass), not the actual type SubClass is considered for resolving the method call. It actually makes sense because you're not looking at the actual instance of an object when calling a static function.

Static methods are redefined not overridden...

If you try to override the static method then it will be treated as a non overridden method of the sub class.

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!