Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes generics question.. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "generics question.." Watch "generics question.." New topic
Author

generics question..

medhaj hambi
Ranch Hand

Joined: Jun 04, 2008
Posts: 34
Can any body explain me how polymorphism works with generics pbly with a good example and the minor glitches to remember for the SCJP6 exam ?
Also pl correct me if I am wrong...
You can in no way add to the collection using the wild card notation the subtypes of the types you specified as part of your signature
but
you can just allow to pass them(subtypes) as a actual parameter into the method signature....say for example
is a method.
you can call this method saying addme ( Doglist ) where doglist is a list of type Dog ...but you cannot actually add the elements of type dog to this collection where it actually expects the elements to be of type animal and only animal.
And if I am right in this, my question is in what cases do we use this kind of scenarios wherein we can just pass in as part of the method arguments but we cannot actually ADD anything of the subtype or the super type into the collection. I mean how is this concept being used in the real world java programes...I am new to java programming so pl bare with me if I ask petty issues.
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9293
    
  17

If you try, you cannot add elements to this collection, but you can surely retrieve elements from this collection. So you might need a method which takes a list of animals and do something on the objects which all animals can do



SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
medhaj hambi
Ranch Hand

Joined: Jun 04, 2008
Posts: 34
but here's my questions though ....okay...you can call the methods which are being used by the animals class...thats true...I agree with you...
but....you pass in say ....doglist i.e list doglist<dog> into the method as argument...and then, can you actually use those dog objects to call the methods of the animal class (animal being its super class) like say for example...doeat() or some thing like that ???

If that is possible, the only thing that is not possible doing w.r.t typed generics is that you cannot basically ADD the subtypes of the types you specified...Am I right in assuming this ? or

Are there any other minor gliteches you can think of that I need to understand here ..?
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9293
    
  17

Of course you can call doEat on an instance of Dog class. Super class methods can be called on a sub-class object (using the super-class or sub-class reference)...
 
Consider Paul's rocket mass heater.
 
subject: generics question..