Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.help > #768

Re: generics

From markspace <-@.>
Newsgroups comp.lang.java.help
Subject Re: generics
Date 2011-06-13 17:49 -0700
Organization A noiseless patient Spider
Message-ID <it6b6u$a7v$1@dont-email.me> (permalink)
References <AqGdnSMWq6oC5mvQnZ2dnUVZ7rOdnZ2d@brightview.co.uk>

Show all headers | View raw


On 6/13/2011 2:05 PM, Neil Morris wrote:

> Cage<Lion> lionCage=new Cage<lion>
>
> Cage<cat> catCage=new Cage<cat>
>
> with the above definitions Cage is a subclass of Collection, but with
> generics as i understand it the various cages ie Cage<animal> Cage<lion>
> and Cage<cat> are not interchangable as below
>
> lionCage.add(catCage)// not allowed!!! even though lionCage and castCage
> are subclasses of Collection
>
> could this be because that the various Cages take differant parameters?


Right.  Generics are invariant.  Most types you are used to are 
covariant.  Covariant means a subclass of one is-a class of its super 
classes.

   Animal c = new Cat();  // fine

Animal and Cat are covariant.

Invariant means you can't do that.

   Cage<Animal> ca = new Cage<Cat>();  // oops

This is a syntax error.  Cat cages and Animal cages are invariant. 
Because an Animal cage may hold other types of animals than just cats, 
you can't substitute one for the other.

Note however the classes are still covariant, which most times when you 
are trying to do something like this is what you want instead.

   Cage<Animal> ca = new Cage<Animal>();
   ca.add( new Cat() );

This is fine, because Animal and Cat are covariant (still).  A cat can 
go in a cage that fits any animal.



Back to comp.lang.java.help | Previous | NextPrevious in thread | Next in thread | Find similar


Thread

generics Neil Morris <neil.morris4@googlemail.com> - 2011-06-13 22:05 +0100
  Re: generics markspace <-@.> - 2011-06-13 17:49 -0700
  Re: generics Joshua Cranmer <Pidgeot18@verizon.invalid> - 2011-06-14 01:48 -0400
  Re: generics Ian Shef <invalid@avoiding.spam> - 2011-06-14 19:45 +0000
  Re: generics Neil Morris <neil.morris4@googlemail.com> - 2011-06-14 21:31 +0100
    Re: generics markspace <-@.> - 2011-06-14 14:21 -0700
      Re: generics Lewis Bloch <lewisbloch@google.com> - 2011-06-16 07:05 -0700
        Re: generics Patricia Shanahan <pats@acm.org> - 2011-06-16 11:40 -0700
        Re: generics Gene Wirchenko <genew@ocis.net> - 2011-06-16 15:14 -0700

csiph-web