Forums Register Login

Co and contravariance

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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..!!
+Pie Number of slices to send: Send
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.
Mo-om! You're embarassing me! Can you just read a tiny ad like a normal person?
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 642 times.
Similar Threads
Unable to understand reason for ClassCastException
Covariant problem
output
Doubt with constructor overloading
Runtime "Exception in thread "main" '
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 06:22:19.