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

后端 未结 3 1859
攒了一身酷
攒了一身酷 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 18:02

    I see nothing wrong with how the compiler treated you, be your methods static or otherwise. Just the next couple of lines in the documentation say:

    This rule allows for covariant return types - refining the return type of a method when overriding it. If R1 is not a subtype of R2, a compile-time unchecked warning occurs unless suppressed by the SuppressWarnings annotation (§9.6.3.5).

    Clear. R1 must be a subtype of R2 like Integer is to another Integer or to Number. String is not subtype of void.

    Documentation says: "compile-time unchecked warning occurs...". But what I noticed is that a full-fledged compilation error awaits.

    Inheritance still works as expected. Remove your child method and you 'd have access to the parent's, static or otherwise.

提交回复
热议问题