Java 9 Anonymous Inner Classes Improvement

Java 9 introduced a new feature that allows us to use diamond operator with anonymous classes. Using the diamond with anonymous classes was not allowed in Java 7.

In Java 9, as long as the inferred type is denotable, we can use the diamond operator when we create an anonymous inner class.

Data types that can be written in Java program like int, String etc are called denotable types. Java 9 compiler is enough smart and now can infer type.

Note: This feature is included to Java 9, to add type inference in anonymous inner classes.

Let's see an example, in which we are using diamond operator with inner class without specifying type.


Java 9 Anonymous Inner Classes Example

Output:

Java9

Although we can specifying type in diamond operator explicitly and compiler does not produce any error message. See, the following example, type is specified explicitly.


Java 9 Anonymous Inner Classes Example

And we get the same result.

Output:

Java9

What happens? If we compile the following code using Java 8.


Anonymous Inner Class Example

Java 8 compiler throws compile time error because it can't infer type. The error message looks like the below.

Output:

TypeInferExample.java:7: error: cannot infer type arguments for ABCD<T>
		ABCD<String> a = new ABCD<>() {
		                         ^
  reason: cannot use '<>' with anonymous inner classes
  where T is a type-variable:
    T extends Object declared in class ABCD
1 error





Latest Courses