Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help in generics....

 
Nitish Bangera
Ranch Hand
Posts: 537
Eclipse IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


This question is from SCJP 6 khalid mughal. The answer to this question is b and c.

well i understand that car can be added but how is sedan put because it says car or super of car(Vehicle or Object).....

Also please explain the other <? extends Car> also.
 
Muhammad Khojaye
Ranch Hand
Posts: 449
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For Garage<? super Car> we can pass either Car or any subclass of the Car to the add() method, but we cannot pass a super class of Car. Also see this
 
Nitish Bangera
Ranch Hand
Posts: 537
Eclipse IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess i confused myself..... This example is like Garage<? super Car> g = new Garage<Car/SUpertype>();

I confused it to to the example given in K&B page 619 where they pass List<Animal> a. reference "a" is passed to a method(List<? super Dog> e) But still a little confusion..... why does it allow as we pass a list<Animal> to a method(list<? super Dog>.)

with raw type object references its not possible as the compiler has no idea which instance it points to or which super type it is going to point to.

I guess i understand a little bit over the problem here..... It is because the V in garage cannot be determined at compile time where as in animal and dog it was determined at compile time that the super of dog is animal.
 
Nitish Bangera
Ranch Hand
Posts: 537
Eclipse IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I really confused myself big time...but i am clear now. When we pass a List<animal> a to a method(List<? super Dog> e)..here we are dealing with references and the compiler knows it. Well if we are talking about List<? super Dog> a = something. compiler really doesn't know what the something object will be that's why we cannot add anything into the list.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic