• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Generics  RSS feed

 
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...
 
Saloon Keeper
Posts: 9145
173
  • 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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!