Why is there no parameter contra-variance for overriding?

后端 未结 6 1159
借酒劲吻你
借酒劲吻你 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:12

    Thanks to Donroby for his answer above - I'm just extending on it.

    interface Alpha
    interface Beta
    interface Gamma extends Alpha, Beta
    class A {
        public void f(Alpha a)
        public void f(Beta b)
    }
    class B extends A {
        public void f(Object o) {
            super.f(o); // What happens when o implements Gamma?
        }
    }
    

    You're falling on a problem akin to the reason multiple implementation inheritance is discouraged. (If you try to invoke A.f(g) directly, you'll get a compile error.)

提交回复
热议问题