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.)
    1. AnimalHouse<Animal> house =
          new AnimalHouse<Cat>();
      
    2. AnimalHouse<Cat> house =
          new AnimalHouse<Animal>();
      
    3. AnimalHouse<?> house =
          new AnimalHouse<Cat>();
      house.setAnimal(new Cat());
      
    4. 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.


Problems with the examples? Try Compiling and Running the Examples: FAQs.
Complaints? Compliments? Suggestions? Give us your feedback.

Previous page: Summary of Generics
Next page: Packages