Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Co and contravariance

 
Pho Tek
Ranch Hand
Posts: 782
Chrome Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is co- and contravariance a concept related to inheritance or can it apply to normal method parameters ?

e.g.


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
 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 correct..in order to avoid such condition..Java has a concept called upcasting

so compiler will allow following to work:

Main2.swallow((Grass)f_);

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..!!
 
Pho Tek
Ranch Hand
Posts: 782
Chrome Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
e.g.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic