Why is it allowed only contravariance of the input parameters of the method in accordance with the Liskov principle of substitution?

I tried to find good examples of why contra-variance is the only variance allowed for the input parameters of the method in accordance with the Liskov substitution principle, but so far none of the examples have answered completely, I doubt it.

I tried to create a counter example that could prove the above statement, but I'm not sure about that. Suppose we have the following classes:

class Z {...}

class X extends Z {...}

class Y extends X {...}

class A { 
    void m(X x);
    ...
}

class B extends A {
    void m(Y y);  // Overriding inherited method m using covariance (by contradiction)
    ...
}

Now suppose I have the following situation:

B b = new B();
A a = b; // Allowed because b is also an A object (B extends A)

Now, since the static type ais equal a, theoretically we should be able to pass objects Xto the method mon a(not sure what the LSP says about this):

a.m(new X());

( , LSP ), , , a B, , B m Y, X.

, , m B, Z X, .

( ) , contra-variance .

? , ? !

+4

Source: https://habr.com/ru/post/1611313/


All Articles