Path: csiph.com!x330-a1.tempe.blueboxinc.net!feeder1.hal-mli.net!weretis.net!feeder1.news.weretis.net!news.swapon.de!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail From: markspace <-@.> Newsgroups: comp.lang.java.help Subject: Re: generics Date: Mon, 13 Jun 2011 17:49:32 -0700 Organization: A noiseless patient Spider Lines: 44 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Tue, 14 Jun 2011 00:49:35 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="9mIMLLWQE/uBQz+Vsit8fg"; logging-data="10495"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18BKz6BKzvL4tr50tXpTqf2zNCRlkW4naw=" User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.17) Gecko/20110414 Thunderbird/3.1.10 In-Reply-To: Cancel-Lock: sha1:s1fDfooOCa8pp43AezQ6uaG//6M= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.help:768 On 6/13/2011 2:05 PM, Neil Morris wrote: > Cage lionCage=new Cage > > Cage catCage=new Cage > > with the above definitions Cage is a subclass of Collection, but with > generics as i understand it the various cages ie Cage Cage > and Cage 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 ca = new Cage(); // 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 ca = new Cage(); 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.