aspose file tools*
The moose likes Java in General and the fly likes type safety Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "type safety" Watch "type safety" New topic
Author

type safety

saravanan ragunathan
Ranch Hand

Joined: Aug 02, 2010
Posts: 84
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?



"I Love Java Ranch"
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4422
    
    8

Because Cat IS-AN Animal. That's the whole point of inheritance.
Martin Vajsar
Sheriff

Joined: Aug 22, 2010
Posts: 3610
    
  60

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

Joined: Aug 02, 2010
Posts: 84
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

Joined: Apr 06, 2010
Posts: 4422
    
    8

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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: type safety