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

后端 未结 3 438
别跟我提以往
别跟我提以往 2020-12-18 17:47

My understanding was that static variables and static methods are of a class, not of the class objects. So an Override of a static method won\'t work in Java, a

3条回答
  •  长情又很酷
    2020-12-18 18:09

    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.

提交回复
热议问题