| Author |
Co and contravariance
|
Pho Tek
Ranch Hand
Joined: Nov 05, 2000
Posts: 757
|
|
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
|
 |
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 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..!!
|
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: 757
|
|
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.
|
 |
 |
|
|
subject: Co and contravariance
|
|
|