Why is there no parameter contra-variance for overriding?

后端 未结 6 1173
借酒劲吻你
借酒劲吻你 2020-12-02 20:36

C++ and Java support return-type covariance when overriding methods.

Neither, however, support contra-variance in parameter types - instead, it translates to overl

6条回答
  •  星月不相逢
    2020-12-02 21:08

    Thanks to donroby's and David's answers, I think I understand that the main problem with introducing parameter contra-variance is the integration with the overloading mechanism.

    So not only is there a problem with a single override for multiple methods, but also the other way:

    class A {
        public void f(String s) {...}
    }
    
    class B extends A {
        public void f(String s) {...} // this can override A.f
        public void f(Object o) {...} // with contra-variance, so can this!
    }
    

    And now there are two valid overrides for the same method:

    A a = new B();
    a.f(); // which f is called?
    

    Other than the overloading issues, I couldn't think of anything else.

    Edit: I've since found this C++ FQA entry (20.8) which agrees with the above - the presence of overloading creates a serious problem for parameter contra-variance.

提交回复
热议问题