There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances ofNumberor its subclasses. This is what bounded type parameters are for.To declare a bounded type parameter, list the type parameter's name, followed by the
extendskeyword, followed by its upper bound, which in this example isNumber. Note that, in this context,extendsis used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).
By modifying our generic method to include this bounded type parameter, compilation will now fail, since our invocation of/** * This version introduces a bounded type parameter. */ public class Box<T> { private T t; public void add(T t) { this.t = t; } public T get() { return t; } public <U extends Number> void inspect(U u){ System.out.println("T: " + t.getClass().getName()); System.out.println("U: " + u.getClass().getName()); } public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(); integerBox.add(new Integer(10)); integerBox.inspect("some text"); // error: this is still String! } }inspectstill includes aString:Box.java:21: <U>inspect(U) in Box<java.lang.Integer> cannot be applied to (java.lang.String) integerBox.inspect("10"); ^ 1 errorTo specify additional interfaces that must be implemented, use the
&character, as in:
<U extends Number & MyInterface>
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é: