Java 9 Diamond Operator for Anonymous Inner Classes

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. In this article, JavaSampleApproach will introduce Java 9 Diamond Operator that can simplifies code and improves readability.

1. Diamond Operator Problem with Anonymous Inner Classes

Assume that we have MyHandler class:

With Java 8, we can write code like this for Anonymous Class:

But how about the cases with Diamond Operator as below:

We get the compile error: ‘<>‘ cannot be used with anonymous classes.

2. Java 9 Diamond Operator Improvement

Java 9 allows the Diamond Operator for Anonymous Inner Classes. Now we can write code easily without compile error:

SOURCE CODE

MyHandler.java

MainApp.java

Run code, the result shows:

By JavaSampleApproach | March 26, 2017.


Related Posts


Got Something To Say:

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

*