Signature difference when hiding static method in a subclass

后端 未结 4 1823
半阙折子戏
半阙折子戏 2020-12-09 11:00

Recently I was playing around with some simple Java code using main methods to quickly test the code I wrote. I ended up in a situation where I had two classes

4条回答
  •  不知归路
    2020-12-09 11:31

    The 'extends' keyword means that you are inheriting the methods from Class A when you declare Class B. Since you Class A is the parent class of Class B, the main method's declaration still lies in Class A despite the fact that you are redefining it in Class B.

    When you are dealing with static methods, the parent class method is not overwritten by the subclass, it is simply hidden.

    http://docs.oracle.com/javase/tutorial/java/IandI/override.html

    Can provide more detail but here is an excerpt:

    The distinction between hiding a static method and overriding an instance method has important implications:

    The version of the overridden instance method that gets invoked is the one in the subclass. The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.


    original answer

    This constraint is forced by the compiler to help simplify inheritance in more complicated hierarchies.

    Take the toString() method for example. It is inherited by every object in Java, imagine if you were able to override the declaring of this method to allow subclasses to throw different exceptions. That is a recipe for disaster in terms of handling all of those potentially new exceptions.

    TLDR- The compiler forces you to obey the parent class function definition so other programmers can sleep at night.

提交回复
热议问题