If static methods can't be overridden, how its working here (For Java)?

☆樱花仙子☆ 提交于 2019-11-29 09:02:56

First of all there are different mechanisms involved here: Overriding and Shadowing (also called hiding).

1) Static methods cannot be overriden as they are attached to the class they are defined in. However, you can shadow/hide a static method as you are doing with your Parent/Child class. This means, the method gets replaced in the Child class but is still available from the Parent class.

It gets more obvious that you are not overriding when you are calling the static methods from instances of those classes (and not using the Class.staticMethod() invocation).

Parent parent = new Parent();
Child child1 = new Child();
Parent child2 = new Child();

parent.StaticMethod();
child1.StaticMethod();
child2.StaticMethod();

the output is

Static method from Parent
Static method from Child
Static method from Parent

The answer is the dispatch of the methods. You can grab the source code here

2) The dispatch finds the method on the Parent class. There is no dynamic dispatch as that the runtime type is used to find the method handle. It uses the compile time type. Remind: Calling static methods from instances is considered bad practice since things like above can happen and are easy to be overlooked.

3) With finalyou declare that the method cannot be overridden neither shadowed/hidden.

You are confusing overriding with hiding

Although it is discouraged to ask 3 questions in one post, I am still willing to answer them.

  1. Static methods cannot be overridden because there is no point of doing that. In your case, If you want to override the static method you can just call the method and add your own implementation after that or you just create another method.

  2. So now that you know that static methods cannot be overridden. But you are asking why the third code works? The third code is the code with

    public class Child extends Parent {}

right? Although static methods cannot be overridden, they can be inherited. What you are doing is inheriting Parent so that is completely fine!

  1. Now let me tell you, in your first code sample you are hiding the method in the Parent class, not overriding. That's why you get the output. A final keyword means the method can never be changed, not even hidden. So that's why.
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!