Computer >> Computer tutorials >  >> Programming >> Java

How can we use a diamond operator with anonymous classes in Java 9?


The diamond operator has introduced in Java 7 to make code more readable, and it can't be used for anonymous inner classes. In Java 9, the diamond operator can be used with an anonymous inner class to improve the readability of code.

In Java 9, we can use the diamond <> operator in anonymous classes as below:

Example

public class DiamondOperatorTest {
   public static void main(String args[]) {
      Handler<Integer> intHandler = new Handler<>(1) {
         @Override
         public void handle() {
            System.out.println(data);
         }
      };
      intHandler.handle();

      Handler<? extends Number> intHandler1 = new Handler<>(2) {
         @Override
         public void handle() {
            System.out.println(data);
         }
      };
      intHandler1.handle();

      Handler<?> handler = new Handler<>("test") {
         @Override
         public void handle() {
            System.out.println(data);
         }
      };
      handler.handle();
   }
}

abstract class Handler<T> {
   public T data;
   public Handler(T data) {
      this.data = data;
   }
   abstract void handle();
}

Output

1
2
test