• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics question

 
Saroja Penn
Greenhorn
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An ArrayList<Animal> can accept references of type Dog, Cat, or any other
subtype of Animal (subclass, or if Animal is an interface, implementation).

The above line is from the 2-minute drill of Generics chapter.

Could anyone please explain what this means? I cannot follow what it says. I thought List<Animal> takes only List<Animal>. Please explain with a small example.

Appreciate any help
Thank you.
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's referring to the elements that you can insert into the list object. You can put any Animal object, including subclass instances, into an List<Animal>.

But you're correct that a List<Animal> reference variable can only be safely assigned a List<Animal> object.
 
Saroja Penn
Greenhorn
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, Kelvin.

Its clear now.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic