Java 9 中,我們可以在匿名類中使用 <> 操作符
阿新 • • 發佈:2018-12-10
不說了,直接上程式碼:
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 }; 21n2.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 }