Why is return-type covariance enforced for hidden static methods?

后端 未结 3 1855
攒了一身酷
攒了一身酷 2021-02-02 17:36

This code won\'t compile because of the String return type of the staticMethod in Child.

class Parent {
    static void st         


        
3条回答
  •  旧巷少年郎
    2021-02-02 17:49

    String is not a subtype of void. Now coming to the actual question :

    The crux of this limitation is the fact that static methods do get inherited in Java but cannot be overriden. If we have to find the motivation for compile-time checking of return types of static methods, the real question to be asked is Why are static methods inherited in Java but can't be overriden?

    The answer is simple.

    static methods can't be overriden because they belong to a class and not an instance. If you want to know the motivation behind this, you can take a look at this question that already has some answers. static methods are allowed to be inherited because there are countless situations where a subclass would want to reuse a static method without having to repeat the same code. Consider a crud example of counting the number of instances of a class :

    class Parent {
       private static int instanceCount = 0;
    
       public Parent() {
           ++instanceCount;
       }
    
       public static int staticMethod() { 
           return instanceCount;   
       }
    
       //other non-static/static methods
    }
    
    class Child extends Parent {
        //.. other static/non-static methods
    }
    

    Parent knows how to count the number of instances that were created of itself. Child is a Parent so Child should ideally know how to count instances of itself as well. If static members were not inherited, you would have to duplicate the code in Parent within Child as well.

提交回复
热议问题