Questions and Exercises: Generics (The Java™ Tutorials > Learning the Java Language > Generics)
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

  ATENCIÓN: La traducción de esta documentación es un esfuerzo personal y voluntario. NO es un documento oficial del propietario de la tecnología Java, Oracle, ni está patrocinado por esta empresa.

Los documentos originales y actualizados (en inglés) están disponibles en: http://docs.oracle.com/javase/tutorial/. La versión disponible en este sitio es la publicada en Marzo de 2008 (más información en: "What's new and What's Old? The History of the Tutorial").

Dirige cualquier comentario, petición, felicitación, etc. a tutorialesjava@codexion.com.

Si quieres ayudar a mantener en funcionamiento esta web, colaborar con la traducción de estos documentos o necesitas que se traduzca algún capítulo en concreto puedes invitarme a un café: