I cannot understand the use of 'super' keyword in this case.
Suppose I have dog extending Animal and the following code:
This doesn't let me add its superclass Animal.
So my problem is, what is the use of 'super'.
what wouldn't I just use dog without super?
But when I do this:
It compiles fine, BUT still doesn't let me add an Animal()?
Intuitively Animals (superclass) shouldnt be allowed to get added in to dog reference List, but my problem is why use super in this case.
what is the reason that I have a dog type reference and an Animal type List, but I can ONLY add dogs?
When you use the <? super Dog> syntax, you are telling the compiler you can accept the type on the right hand side of super or any of its supertype.
Thus a collection declared as any supertype of Dog will be able to refer a collection of Dog's supertype,(Animal) or Object.
However while adding an element to the collection, you can only add the type on the right hand side of super.., i.e Dog. Well a Dog is an animal but an Animal is not a Dog so you can refer to a Collection of type Animal but can not add an animal.
SCJP 5.0 -- 97%
Joined: May 25, 2005
Thank you very much.
So I can define the reference with the <? super> so that the actual collection type (right hand side) can be left hand side or its super type.. but when I add, I can only add whatever I defined on the right hand side.
but any particular use of this?
I know the use super in a method argument, so I can 'add' any supertype of the reference type safely, but why define a reference in this way?
If for example, I say,
But I can only add Animal objects into this, and I even cannot safely call Dog methods on the items inside the dog list.
SO what purpose does this serve?
Isn't this risky? because at compile time, dog list can be a list of Dogs or Animals.
But I cannot invoke Dog methods on the items inside dog list. Because the items can be Dogs or Animals?
Check the link to the generics tutorial. A rule of thumb is that if you use the ? wildcard, you cannot alter a collection in any way. You may still read from a collection for example with an iterator, but you cannot add or remove items. Generics are stripped at runtime, so while the compiler ensures a type safe collection, the JVM cannot be sure of what you add or remove from the collection if a wildcard is used, so you cant add / remove. Its tricky, but after a while and a bit of reading you will grasp it.
be a well encapsulated person, don't expose your privates, unless you public void getWife()!