Easy Tutorial
❮ Java Bitset Class Method Enum ❯

Java 9 Diamond Operator

Java 9 New Features

The diamond operator was introduced in Java 7 to make the code more readable, but it could not be used with anonymous inner classes.

In Java 9, it can be used with anonymous inner classes, thereby enhancing code readability.

Consider the following code before Java 9:

Example

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();
}

Execution output:

1
2
Test

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

Example

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();
}

Execution output:

1
2
Test

Java 9 New Features

❮ Java Bitset Class Method Enum ❯