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
-
Take a look at covariance as this is what is going on here.Suroot– Suroot2011年06月15日 04:13:17 +00:00Commented Jun 15, 2011 at 4:13
3 Answers 3
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
Cameron Skinner
55.3k3 gold badges70 silver badges86 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
gmhk
16k29 gold badges92 silver badges113 bronze badges
Comments
lang-java