4

I was trying to find good examples of why contra-variance is the only variance allowed for method input parameters according to the Liskov Substitution Principle, but until now none of the examples has completely answered ,y doubts.

I was trying to build a counter-example that could prove the statement above, but I am not sure about it. 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 of a is A, theoretically we should be able to pass X objects to the method m on a (not sure what the LSP says about this):

a.m(new X());

At runtime (not sure what the LSP says about runtime and compile-time), on the other hand, this would fail, because a is actually pointing to a B object, but the method overridden in B m only accepts Y objects, which are of subtype X.

If we had allowed contra-variance instead, for example by overriding m in B by specifying the type of the parameter as Z or X, none of this would happen.

This is for now my (and my friend's) only explanation of why we are only allowed to use contra-variance for method parameters.

Is my explanation correct? Are there other situations that can explain this concept more in detail? Concrete examples are appreciated!

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
nbro
  • 15,395
  • 32
  • 113
  • 196
  • Yes, your explanation is correct. There are other cases, I guess they are just variations of the same. You need to be able to treat B as an A, and it shall behave like an A, that's the contract of inheritance. This is not a real question, since you answer it yourself. It's more like starting a discussion about the topic. This will be closed on Stackoverflow, because it is a Q&A site. – Stefan Steinegger Oct 29 '15 at 07:29
  • @StefanSteinegger This is not a discussion, these are just my thoughts, which I am sharing with you in order to understand where I am wrong or where I am right. That's why I am asking: "Is my explanation correct?". If you like to be a funny guy, you failed this time. – nbro Oct 29 '15 at 10:05
  • Don't misunderstand me, I just don't know how this question could be answered in a way that fits in Stackoverflows concepts. I'm just trying to explain this. These are your thoughts; where is the question then? If it is: "Am I right?", you expect an answer like "yes, you're right" (since this is the case). Everything else is a discussion. – Stefan Steinegger Oct 29 '15 at 12:38
  • I think you pretty much covered it. I have nothing to add. – Dave Schweisguth Feb 09 '16 at 06:23

0 Answers0