☰
Java 7 has a new feature called Diamond Operator which helps to make code more readable, but it is still limited with Anonymous Inner Classes.
Java 9 allows diamond with anonymous classes if the argument type of the inferred type is denotable. Prior to Java 9, we need to specify the type argument to anonymous class.
Check out this below code in Java 8.
public abstract class MyHandler {
// constructor, getter, setter...
abstract void handle();
}
MyHandler intHandler = new MyHandler(1) {
public void handle() {
// handling code...
}
};
Works fine without any issues. Now how about the cases with Diamond Operator as below
MyHandler intHandler = new MyHandler<>(10) { // Anonymous Class };
MyHandler<?> handler = new MyHandler<>(""One hundred") { // Anonymous Class };
We get the compile error: ‘<>‘ cannot be used with anonymous classes.
Java 9 allows the Diamond Operator for Anonymous Inner Classes.
MyHandler intHandler = new MyHandler<>(1) {
@Override
public void handle() {
// handling code...
}
};
MyHandler<? extends Integer> intHandler1 = new MyHandler<>(10) {
@Override
void handle() {
// handling code...
}
};
MyHandler<?> handler = new MyHandler<>("One hundred") {
@Override
void handle() {
// handling code...
}
};