参考地址: 1. http://www.cnblogs.com/lwbqqyumidi/p/3837629.html2. http://www.cnblogs.com/abcwt112/p/4735068.html3. http://www.cnblogs.com/chyu/p/4630798.html
1 package learn.JavaBasics.Class; 2 3 public class GenericDemo { 4 private class Test<E> { 5 private E i; 6 7 public E get() { 8 return this.i; 9 } 10 11 public void set(E str) { 12 this.i = str; 13 } 14 15 public void echo() { 16 System.out.println("echo test"); 17 } 18 } 19 20 public interface testInterface<E> { 21 public E print(); 22 } 23 24 /** 25 * @param args 26 */ 27 public static void main(String[] args) { 28 // TODO Auto-generated method stub 29 GenericDemo g = new GenericDemo(); 30 31 Test<Integer> a = g.new Test<Integer>(); 32 a.set(112); 33 System.out.println(a.get()); 34 35 Test<String> s = g.new Test<String>(); 36 s.set("hello"); 37 System.out.println(s.get()); 38 39 g.put(a); 40 g.put(s); 41 42 // g.putExtends(a); 43 g.putExtends(s); 44 45 g.putSuper(a); 46 // g.putSuper(s); 47 48 System.out.println("*****"); 49 50 g.question(a).echo(); 51 g.question(s).echo(); 52 53 String is = new testInterface<String>() { 54 @Override 55 public String print() { 56 // TODO Auto-generated method stub 57 58 return "Interface Generic Test"; 59 } 60 }.print(); 61 62 System.out.println(is); 63 } 64 65 public void put(Test<?> t) { 66 System.out.println(t.get()); 67 } 68 69 public void putExtends(Test<? extends String> t) { 70 System.out.println(t.get()); 71 } 72 73 public void putSuper(Test<? super Integer> t) { 74 System.out.println(t.get()); 75 } 76 77 public Test<?> question(Test<?> t) { 78 System.out.println(t); 79 return t; 80 } 81 }
时间: 2024-12-07 09:12:02