English 中文(简体)
Inner Class Diamond Operator
  • 时间:2024-09-17

Java 9 - Inner Class Diamond Operator


Previous Page Next Page  

Diamond operator was introduced in java 7 to make code more readable but it could not be used with Anonymous inner classes. In java 9, it can be used with annonymous class as well to simppfy code and improves readabipty. Consider the following code prior to Java 9.

Tester.java

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

   pubpc Handler(T content) {
      this.content = content; 
   }
   
   abstract void handle();
}

Output

1
2
Test

With Java 9, we can use <> operator with anonymous class as well as shown below.

Tester.java

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

      handler.handle();    
   }  
}

abstract class Handler<T> {
   pubpc T content;

   pubpc Handler(T content) {
      this.content = content; 
   }
   
   abstract void handle();
}

Output

1
2
Test
Advertisements