my dog learned polymorphism
The moose likes Beginning Java and the fly likes Co and contravariance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Co and contravariance" Watch "Co and contravariance" New topic

Co and contravariance

Pho Tek
Ranch Hand

Joined: Nov 05, 2000
Posts: 776

Is co- and contravariance a concept related to inheritance or can it apply to normal method parameters ?


So I get a compile-time error because the method parameters to swallow is covariant i.e. it only accepts Grass and its subtypes.

Am I correct in my reasoning ? Thanks
Sunny Jain
Ranch Hand

Joined: Jul 23, 2007
Posts: 433

although legally it should accept Grass and its subtype..!!
but consider the following case:

Food f_ = new Grass();

here actual object is of type Grass..
so in this case:
Main.swallow(f_) should work..but compiler give you complaint..!!

but this is order to avoid such condition..Java has a concept called upcasting

so compiler will allow following to work:


now it works finally..but delima is..
if Food f_ = new Food();

Then also it will work fine..!! at this time it will give you run time exception..!! ClassCastException..!!

Thanks and Regards,
SCJP 1.5 (90%), SCWCD 1.5 (85%), The Jovial Java, java.util.concurrent tutorial
Pho Tek
Ranch Hand

Joined: Nov 05, 2000
Posts: 776

Well let's supposed that casting of any sort is disallowed.
Then the parameter is covariant.

However if the parameter type is a generic type & the method is a generic method; then it is contravariant.
I'm thinking out loud here - and would appreciate some feedback/correction.
I agree. Here's the link:
subject: Co and contravariance
It's not a secret anymore!