The Diamond operator was introduced in Java 7 to make the code more readable, but cannot be used with anonymous inner classes. In Java 9, you can use the diamond operator with anonymous inner classes to improve code readability.
In Java 9, we can use the diamond<>operator in an anonymous class like below:
public class DiamondOperatorTest { public static void main(String args[]) { <strong>Handler<Integer></strong> intHandler = new <strong>Handler<>(1)</strong> { <strong>@Override</strong> public void handle() { System.out.println(data); } }; intHandler.handle(); <strong>Handler<? extends Number></strong><!--? extends Number--> intHandler1 = new <strong>Handler<>(2)</strong> { <strong>@Override</strong> public void handle() { System.out.println(data); } }; intHandler1.handle(); <strong>Handler<?></strong><!--?--> handler = new <strong>Handler<>("test")</strong> { <strong>@Override </strong> public void handle() { System.out.println(data); } }; handler.handle(); } } abstract class Handler<T> { public T data; public Handler(T data) { this.data = data; } abstract void handle(); }
<strong>1 2 test</strong>
The above is the detailed content of How can we use diamond operator with anonymous classes in Java 9?. For more information, please follow other related articles on the PHP Chinese website!