• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

type safety

 
saravanan ragunathan
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when we use type argument
ex: ArrayList<String> in this we cannot add
objects other than String ..
but the below code runs without compilation error



here although i restrict ArrayList only to Animal..
compiler allows both cat and Dog objects
then where the type safety goes?

 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because Cat IS-AN Animal. That's the whole point of inheritance.
 
Martin Vajsar
Sheriff
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Had you really tried to run your example, you'd notice the following line does not compile:
List of animals cannot be assigned list of dogs. Read the generics tutorial carefully to understand why.

When you change that line to
it starts working and Matthew's explanation holds.
 
saravanan ragunathan
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew Brown wrote:Because Cat IS-AN Animal. That's the whole point of inheritance.


i checked the method add in API by expecting wildcards(?) which allows subtypes
but there is no such thing..
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wildcards aren't needed to allow a Cat or a Dog to be added to a list of Animals. There's something called the Liskov Substitution Principle - anywhere an instance of a class us needed, then an instance of any subclass can be used. Google it and you'll get a lot more explanation.

Wildcards are different, and are a way of getting round the problem Martin mentioned above. The generic tutorial will explain more, but make sure you understand how generics work without wildcards first.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic