Studyon Minte9.com
Fundamentals (Docs)

Study

Bounded Type Parameters



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 of Number or its 
subclasses. This is what bounded type parameters are for.

	/**
	 * This version introduces a bounded type parameter.
	 */
	public class GenericTypeDemo3<T> {
	    
	    private T t;
	    
	    public void set(T t) {
		this.t = t;
	    }
	    
	    public T get() {
		return t;
	    }
	    
	    public static void main(String[] args) {
		GenericTypeDemo3<Integer> box1 = new GenericTypeDemo3<Integer>();
		box1.set(new Integer(10));
		box1.inspect("some text"); // failed
	    }
	    
	    public <U extends Number> void inspect(U u) {
		System.out.println("T: " + t.getClass().getName());
		System.out.println("U: " + u.getClass().getName());
	    }
	}

By modifying our generic method to include this bounded type parameter, compilation will now fail, since our 
invocation of inspect still includes a String.

To specify additional interfaces that must be implemented, use the & character, as in:

	<U extends Number & MyInterface>



Generic vs Non-Generic

A class design that acts as a library for the following kinds of media: book, video, and newspaper.

Non-Generic

	import java.util.List;
	import java.util.ArrayList;

	public class LibraryNonGeneric {

	    public class Library {
		private List resources = new ArrayList();
		public void add(Media x) {}
		public Media getLast(){return null;}
	    }
	    
	    interface Media {};
	    interface Book extends Media {};
	    interface Video extends Media {};
	    interface Newspaper extends Media {};
	}

Generic

	import java.util.List;
	import java.util.ArrayList;

	public class LibraryGeneric {

	    public class Library<E extends Media> {
		private List<E> resources = new ArrayList<E>();
		public void add(E x) {}
		public E getLast(){return null;}
	    }
	    
	    interface Media {};
	}


http://docs.oracle.com/javase/tutorial/java/generics/bounded.html