Java 9 Diamond Operator with Anonymous Inner Classes
Diamond operator ‘<>’ was introduced in Java 7 to make instantiation of generic classes easier.
Thus instead of having:
List<Integer> list = new ArrayList<Integer>();
We could have:
List<Integer> list = new ArrayList<>();
But this is not the case for anonymous classes. Let’s say we have Diamond interface:
public interface Diamond<T> {
void run();
}
In Java 8 we can write the code like this:
Diamond<Integer> diamond = new Diamond<Integer>() {
@Override
public void run() {
//run
}
};
But if we want to use here the diamond operator, we will get compile time error
Diamond<Integer> diamond = new Diamond<>() {
@Override
public void run() {
// run
}
};
cannot use '<>' with anonymous inner classes
With Java 9 changes it is possible to use diamond operator in anonymous inner classes:
Diamond<Integer> diamond = new Diamond<>() {
@Override
public void run() {
// run
}
};