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

Asaph
164k25 gold badges204 silver badges204 bronze badges
asked Jun 15, 2011 at 4:02
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.

answered Jun 15, 2011 at 4:04
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.

Asaph
164k25 gold badges204 silver badges204 bronze badges
answered Jun 15, 2011 at 4:04

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

answered Jun 15, 2011 at 4:14

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.