不说了,直接上代码:
1 public class NewTest { 2 3 public static void main(String[] args) { 4 N<Integer> n1 = new N<Integer>(1) { 5 @Override 6 void handler() { 7 System.out.println("这个是数字:" + this.getContent()); 8 9 } 10 11 }; 12 n1.handler(); 13 14 var n2 = new N<String>("这个是字符串,用var定义临时变量哦") { 15 @Override 16 void handler() { 17 System.out.println("这个是字符串文本哦:" + this.getContent()); 18 19 } 20 }; 21 n2.handler(); 22 23 /*我可以匿名哦,JDK9支持哦*/ 24 N<?> n3 = new N<>("object") { 25 @Override 26 void handler() { 27 System.out.println("object:"+this.getContent()); 28 } 29 }; 30 n3.handler(); 31 } 32 33 } 34 35 36 abstract class N<T> { 37 38 private T content; 39 40 public N(T content) { 41 this.content = content; 42 } 43 44 public T getContent() { 45 return content; 46 } 47 48 public void setContent(T content) { 49 this.content = content; 50 } 51 52 abstract void handler(); 53 54 }