Trail: Learning the Java Language
Lesson: Generics
Questions and Exercises
Home Page > Learning the Java Language > Generics
Questions and Exercises: Generics

Questions

1. Consider the following classes:
public class AnimalHouse<E> {
    private E animal;
    public void setAnimal(E x) {
        animal = x;
    }
    public E getAnimal() {
        return animal;
    }
}

public class Animal{
}

public class Cat extends Animal {
}

public class Dog extends Animal {
}
For the following code snippets, identify whether the code:
  • fails to compile,
  • compiles with a warning,
  • generates an error at runtime, or
  • none of the above (compiles and runs without problem.)
a. AnimalHouse<Animal> house = new AnimalHouse<Cat>();

b. AnimalHouse<Dog> house = new AnimalHouse<Animal>();

c. AnimalHouse<?> house = new AnimalHouse<Cat>();
   house.setAnimal(new Cat());

d. AnimalHouse house = new AnimalHouse();
   house.setAnimal(new Dog());

Exercises

  1. Design a class that acts as a library for the following kinds of media: book, video, and newspaper. Provide one version of the class that uses generics and one that does not. Feel free to use any additional APIs for storing and retrieving the media.

Check your answers.

Previous page: Summary of Generics
Next page: Packages