• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generics  RSS feed

 
Sudhanshu Mishra
Ranch Hand
Posts: 238
1
Eclipse IDE Fedora Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I have this question from K&B book,and i am confused regarding a solution.

Q:
interface Hungry<E> { void munch(E x); }
interface Carnivore<E extends Animal> extends Hungry<E> {}
interface Herbivore<E extends Plant> extends Hungry<E> {}
abstract class Plant {}
class Grass extends Plant {}
abstract class Animal {}
class Sheep extends Animal implements Herbivore<Sheep> {
public void munch(Sheep x) {}
}
class Wolf extends Animal implements Carnivore<Sheep> {
public void munch(Sheep x) {}
}
Which of the following changes (taken separately) would allow this code to compile?
(Choose all that apply.)

//other options are clear to me
D. Change the Sheep class to
class Sheep extends Plant implements Carnivore<Wolf> {
public void munch(Wolf x) {}
}
E. Change the Wolf class to
class Wolf extends Animal implements Herbivore<Grass> {
public void munch(Grass x) {}
}


Now i am unable to get why these two options won't do?
May be i am again making a silly mistake,but please be kind to correct me.
Thanks...
 
Stephan van Hulst
Saloon Keeper
Posts: 7987
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
D won't do because the Sheep would be a Plant, and then Wolf can not be a Carnivore<Sheep>.

E won't do because Sheep is broken, and changing Wolf won't do anything to fix it (Sheep can not be a Herbivore<Sheep>, because Sheep is an Animal).

you should also UseCodeTags. They will make your code easier to read.
 
Sudhanshu Mishra
Ranch Hand
Posts: 238
1
Eclipse IDE Fedora Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Stephen.
I got it.We can rule out E straight away as it does not solves problem of Sheep.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!