Why is it that we cannot override static and final methods? [duplicate]

帅比萌擦擦* 提交于 2019-12-18 12:27:54

问题


I am trying to understand why we can't override static and final methods. I do not get the purpose behind it.


回答1:


final methods can't be overriden, because that's what final is designed to do: it's a sign saying "do not override this".

static methods can't be overriden, because they are never called in a polymorphic way: when you call SomeClass.foo() it will always be the foo method of SomeClass, no matter if there is another ExtendedSomeClass that has a much groovier foo method.




回答2:


final is used to avoid overriding. And a static method is not associated with any instance of a class so the concept is not applicable.




回答3:


The reason for not overriding static method is that Static methods are treated as global by the JVM so there are not bound to an object instance at all. Similarly final methods cant be overriddent because when you say a method as final then it mean you are saying to the JVM that this method cannot be overridden.

The wiki has a very important misconception about final. Do read that!

A final method cannot be overridden or hidden by subclasses.[2] This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.[3]

A common misconception is that declaring a class or method as final improves efficiency by allowing the compiler to directly insert the method wherever it is called (see inline expansion). But because the method is loaded at runtime, compilers are unable to do this. Only the runtime environment and JIT compiler know exactly which classes have been loaded, and so only they are able to make decisions about when to inline, whether or not the method is final.[4]




回答4:


Static methods are covered here.

Final methods cannot be overridden because the purpose of the "final" keyword is to prevent overriding.




回答5:


Final cannot be overridden because that is the purpose of the keyword, something that cannot be changed or overridden.

The purpose of inheritance and polymorphism is to have objects of same class implementing methods (not the names but the code in the methods) in different ways. And static methods cannot be accessed by objects because they are a part of the class not the instance. So there is no purpose to overriding the Static methods. And you can have a static method in subclass by the same name but that won’t be an overridden method.

If you haven't yet read about Inheritance and Polymorphism which are both features of Java, you should and also try to write the code in the question so that SO users can answer with an example.



来源:https://stackoverflow.com/questions/20282027/why-is-it-that-we-cannot-override-static-and-final-methods

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