1

So I have a class cat which implements a interface Vocal, I was wondering why when I created a ArrayList(Vocal) I was able to add instances of cat to it?

Thank You

1
  • Take a look at covariance as this is what is going on here. Commented Jun 15, 2011 at 4:13

3 Answers 3

6

It's because when Cat implements Vocal it's an IS-A relationship: Cat IS-A Vocal.

Since the List<Vocal> accepts anything that is Vocal, adding an instance of Cat is perfectly legal.

Sign up to request clarification or add additional context in comments.

Comments

1

Yes. You will be able to add an instance of any class that is declared to implement Vocal.

Comments

0

In your case, the relationship will be exactly the same

Cats IS A Vocal too.

So that was the reason you are able to add the arraylist of CATS in Vocal Type Arraylist

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.