logo

Inner Class Diamond Operator


Show

The diamond operator is launched in java 7 to make the code more easily readable but it cannot be used with Anonymous inner classes. It can be easily used with anonymous classes as well to simplify code and enhance readability. Below is the code earlier to java 9.

Tester.Java

public class Tester {
   public static void main(String[] args) {
      Handler<Integer> intHandler = new Handler<Integer>(1) {
         @Override
         public void handle() {
            System.out.println(content);
         }
      };
      intHandler.handle();
      Handler<? extends Number> intHandler1 = new Handler<Number>(2) {
         @Override
         public void handle() {
            System.out.println(content);
         }
      };
      intHandler1.handle();
      Handler<?> handler = new Handler<Object>("test") {
         @Override
         public void handle() {
            System.out.println(content);
         }
      };
      handler.handle();    
   }  
}
abstract class Handler<T> {
   public T content;
   public Handler(T content) {
      this.content = content; 
   }
 
   abstract void handle();

}

Result

1
2
Test

But In Java 9, we can use the <> operator with anonymous class as given below.

Tester.java

public class Tester {
   public static void main(String[] args) {
      Handler<Integer> intHandler = new Handler<>(1) {
         @Override
         public void handle() {
            System.out.println(content);
         }
      };
      intHandler.handle();
      Handler<? extends Number> intHandler1 = new Handler<>(2) {
         @Override
         public void handle() {
            System.out.println(content);
         }
      };
      intHandler1.handle();
      Handler<?> handler = new Handler<>("test") {
         @Override
         public void handle() {
            System.out.println(content);
         }
      };

      handler.handle();    
   }  
}

abstract class Handler<T> {
   public T content;

   public Handler(T content) {
      this.content = content; 
   }  

   abstract void handle();
}

Result

1
2
Test