Java 9: Simplify Anonymous Inner Classes with the Diamond Operator
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 annonymous class as well to simplify code and improves readability. Consider the following code prior to Java 9.
Tester.java
Live Demo
public class Tester {
public static void main(String[] args) {
Handler<Integer> intHandler = new Handler<Integer>(1) {
@Override
public void handle() {
System.out.println(content);
}
};
intHandler.handle();
Handler<? extends Number> intHandler1 = new Handler<Number>(2) {
@Override
public void handle() {
System.out.println(content);
}
};
intHandler1.handle();
Handler<?> handler = new Handler<Object>("test") {
@Override
public void handle() {
System.out.println(content);
}
};
handler.handle();
}
}
abstract class Handler<T> {
public T content;
public Handler(T content) {
this.content = content;
}
abstract void handle();
}
Output
1 2 Test
With Java 9, we can use <> operator with anonymous class as well as shown below.
Tester.java
public class Tester {
public static void main(String[] args) {
Handler<Integer> intHandler = new Handler<>(1) {
@Override
public void handle() {
System.out.println(content);
}
};
intHandler.handle();
Handler<? extends Number> intHandler1 = new Handler<>(2) {
@Override
public void handle() {
System.out.println(content);
}
};
intHandler1.handle();
Handler<?> handler = new Handler<>("test") {
@Override
public void handle() {
System.out.println(content);
}
};
handler.handle();
}
}
abstract class Handler<T> {
public T content;
public Handler(T content) {
this.content = content;
}
abstract void handle();
}
Output
1 2 Test
Java
- Java instanceof Operator: A Comprehensive Guide
- Mastering Java Nested and Inner Classes: Types, Examples, and Best Practices
- Mastering Java Anonymous Inner Classes: Definition, Syntax, and Practical Examples
- Mastering Java’s ObjectInputStream: A Comprehensive Guide
- Mastering Java ObjectOutputStream: Serialization, Methods, and Practical Examples
- Mastering Java’s PrintStream Class: Print, Println, and Printf Explained
- Mastering Java Reader Class: Subclasses, Methods, and Practical Example
- Mastering Java Generics – Building Reusable, Type‑Safe Code
- Mastering Java File Operations with java.io – Creation, Reading, Writing & Deletion
- Java Inner Classes Explained: Design, Syntax, and Practical Uses