Java 9 – Anonymous Inner classes and Diamond Operator

Type inference is a feature of Java that was introduced in Java 7. Now, Java compiler can infer type of a data automatically.
For example, if we create an ArrayList then we use the code like:

You can see that Java 7 allows us to use empty diamond operator to avoid code redundancy. But we can use this Java collection only, what about the anonymous class?

If we do the same in Java 7 with anonymous class, means use empty diamond(<>) in an anonymous class then compiler reports an error. See the example below:

Output

error: cannot infer type arguments for CalculateAble
CalculateAble a = new CalculateAble() {
^
reason: cannot use ” with anonymous inner classes

Note: The empty diamond operator with anonymous classes was not allowed in Java SE 7.

This is how we create an anonymous class in Java. It works fine with all the Java versions.

Anonymous class: Java 9 Improvement

Java improved its type inference feature and allowed us to use (diamond) in the anonymous class too. For example, if we create an anonymous class with empty diamond(<>), then the compiler does not report any error and will compile the code successfully.

Example: Anonymous class with diamond operator

Let’s execute this example using Java 9 and higher version and see. It will execute fine.

Output

30

Well, this is all about the use of diamond operator in an anonymous class in Java 9 version.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *