Java 9 Anonymous Inner Classes Improvement

Java 9 Anonymous Inner Classes Improvement

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.

Java 9 Anonymous Inner Classes Example

  1. abstract class ABCD<T>{
  2.     abstract T show(T a, T b);
  3. }
  4. public class TypeInferExample {
  5.     public static void main(String[] args) {
  6.         ABCD<String> a = new ABCD<>() { // diamond operator is empty, compiler infer type
  7.             String show(String a, String b) {
  8.                 return a+b;
  9.             }
  10.         };
  11.         String result = a.show(“Java”,“9”);
  12.         System.out.println(result);
  13.     }
  14. }

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

  1. abstract class ABCD<T>{
  2.     abstract T show(T a, T b);
  3. }
  4. public class TypeInferExample {
  5.     public static void main(String[] args) {
  6.         ABCD<String> a = new ABCD<String>() { // diamond operator is not empty
  7.             String show(String a, String b) {
  8.                 return a+b;
  9.             }
  10.         };
  11.         String result = a.show(“Java”,“9”);
  12.         System.out.println(result);
  13.     }
  14. }

And we get the same result.

Output:

Java9

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


Anonymous Inner Class Example

  1. abstract class ABCD<T>{
  2.     abstract T show(T a, T b);
  3. }
  4. public class TypeInferExample {
  5.     public static void main(String[] args) {
  6.         ABCD<String> a = new ABCD<>() { // diamond operator is empty
  7.             String show(String a, String b) {
  8.                 return a+b;
  9.             }
  10.         };
  11.         String result = a.show(“Java”,“9”);
  12.         System.out.println(result);
  13.     }
  14. }

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

Leave a Reply

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