Saturday, August 14, 2010

Abstracts and Interfaces

Courtesy of SCJP Sun® Certified Programmer for Java™ 6 Study Guide Exam (310-065) (9780071591065)
Chapter 7, 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

interface Carnivore<E extends Plant> extends Hungry<E> {}

Incorrect; compiler will display following error

type parameter Sheep is not within its bound
class Wolf extends Animal implements Carnivore<Sheep> {

 
B. Change the Herbivore interface to

interface Herbivore<E extends Animal> extends Hungry<E> {}

Correct. The problem with the original code is that Sheep tries to implement Herbivore<Sheep> and Herbivore declares that its type parameter E can be any type that extends Plant. Since a Sheep is not a Plant, Herbivore<Sheep> makes no sense—the type Sheep is outside the allowed range of Herbivore’s parameter E. Only solutions that either alter the definition of a Sheep or alter the definition of Herbivore will be able to fix this. 

C. Change the Sheep class to

class Sheep extends Animal implements Herbivore<Plant> {
       public void munch(Grass x) {}
}

Incorrect; compiler will display following error

Sheep is not abstract and does not override abstract method munch(Plant) in Hungry
class Sheep extends Animal implements Herbivore<Plant> {


D. Change the Sheep class to

class Sheep extends Plant implements Carnivore<Wolf> {
       public void munch(Wolf x) {}
}

In this option, Sheep extends Plant while line 2 declares that Carnivore can hold datatypes that extend Animal, hence compiler will display following error

type parameter Sheep is not within its bound
class Wolf extends Animal implements Carnivore<Sheep> {


E. Change the Wolf class to

class Wolf extends Animal implements Herbivore<Grass> {
       public void munch(Grass x) {}
}

This change doesn't make a difference; compiler still gives the following error:

type parameter Sheep is not within its bound
class Sheep extends Animal implements Herbivore<Sheep> {


F. No changes are necessary
Incorrect, please see explanations to previous options

No comments:

Post a Comment