-2

I was testing around polymorphism, and I came up with below code:

public abstract class Animal {

}


public interface Hunter {

}

public class Cat extends Animal implements Hunter {

}


public class Tiger extends Cat {

    public static void main(String[] args){
        //n1
    }

}

I placed on n1:

ArrayList<Tiger> myList = new ArrayList<>();
myList.add(new Cat());

But it fails to compile: I think that it does because Cat is parent of Tiger, and Tiger can only store its children which at the moment it does not have any.

Am I overlooking the real cause of this issue?

Cuban coffee
  • 294
  • 5
  • 14
  • I am not taking about collection, I am just curious whether I am wrong or not with my statement, which is more related to inheritance. – Cuban coffee Dec 06 '15 at 14:48
  • @Cubancoffee out of curiosity, why you have not accepted any answers till now?Your profile says you have asked 8 question but you havent accepted any. Does none of them answer all your quries? – SpringLearner Dec 07 '15 at 04:12
  • A `Cat` is not a `Tiger` and a list of tigers can’t contain a cat. It doesn’t matter whether “Cat is parent of Tiger” or not. All that matters is that `Cat` is not a subtype of `Tiger`. But do you really need us to get confident that a cat is not a tiger? – Holger Dec 07 '15 at 14:49

1 Answers1

3

Compilation error is because you are violating Liskov Substitution Principle

It states that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.).

In your case, you are using super-type (Cat), where sub-type (Tiger) is expected - i.e., in myList.add(...). This is not allowed.

Wand Maker
  • 18,476
  • 8
  • 53
  • 87