YouTip LogoYouTip

Java9 Inner Class Diamond Operator

# Java 9 Diamond Operator [![Image 3: Java 9 New Features](#) Java 9 New Features](#) The diamond operator was introduced in Java 7 to make code more readable, but it could not be used with anonymous inner classes. In Java 9, it can be used with anonymous inner classes, thereby improving code readability. Consider the following code before Java 9: ## Example public class Tester{public static void main(String[]args){HandlerintHandler = new Handler(1){ @Override public void handle(){System.out.println(content); }}; intHandler.handle(); HandlerintHandler1 = new Handler(2){ @Override public void handle(){System.out.println(content); }}; intHandler1.handle(); Handlerhandler = new Handler("test"){ @Override public void handle(){System.out.println(content); }}; handler.handle(); }}abstract class Handler{public T content; public Handler(T content){this.content = content; }abstract void handle(); } The output of the execution is: 12Test In Java 9, we can use the operator in anonymous classes, as shown below: ## Example public class Tester{public static void main(String[]args){HandlerintHandler = new Handler(1){ @Override public void handle(){System.out.println(content); }}; intHandler.handle(); HandlerintHandler1 = new Handler(2){ @Override public void handle(){System.out.println(content); }}; intHandler1.handle(); Handlerhandler = new Handler("test"){ @Override public void handle(){System.out.println(content); }}; handler.handle(); }}abstract class Handler{public T content; public Handler(T content){this.content = content; }abstract void handle(); } The output of the execution is: 12Test [![Image 4: Java 9 New Features](#) Java 9 New Features](#)
← Java9 Multiresolution Image_ApJava9 Try With Resources Impro β†’

YouTip © 2024-2026 | Home | Learn Technology, Build Dreams!

All content is for educational and learning purposes only.