Forums Register Login

Generic Types extending Abstract implementing Interface

+Pie Number of slices to send: Send
Chapter 7, Sierra/Bates, Quiz Question # 6



Which of the following changes (taken separately) would allow this code to compile? (Choose all that apply.)

A. Change the Carnivore interface to



B. Change the Herbivore interface to



C. Change the Sheep class to



D. Change the Sheep class to



E. Change the Wolf class to



F. No changes are necessary





I can understand why B is the answer. However, I cannot understand the explanation for D

And D doesn’t work, because in D we made Sheep extend Plant, now the Wolf class breaks because its munch(Sheep) method no longer fulfills the contract of Carnivore.



How is Wolf class broken?
+Pie Number of slices to send: Send
The following code, which incorporates D does not compile:



Compiler outputs:

Eat.java:11: type parameter Sheep is not within its bound
class Wolf extends Animal implements Carnivore<Sheep> {
^
1 error


Please give a hint, thanks!

+Pie Number of slices to send: Send
Hi Sandra,

By changing Sheep to extend Plant from Animal you have broken the interface contract of Carnivore when used in Wolf. How? By passing it a Sheep which doesn't extend an Animal anymore.

Please let me know if this helps.
+Pie Number of slices to send: Send
@ Faisal: Now I get it. I changed Sheep to extend Animal and now it compiles.
I'm sure glad that he's gone. Now I can read this tiny ad in peace!
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 2745 times.
Similar Threads
K&B collection and generic question
Diubt on Generics, Q.10 from K&b book
page# 616 question# 10
puzzled by this question
K&B -From genric & collections-Self Test
More...

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