Home  >  Article  >  Java  >  How can we use diamond operator with anonymous classes in Java 9?

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

WBOY
WBOYforward
2023-08-27 09:13:02686browse

在Java 9中,我们如何使用钻石操作符与匿名类?

The Diamond operator was introduced in Java 7 to make the code more readable, but cannot be used with anonymous inner classes. In Java 9, you can use the diamond operator with anonymous inner classes to improve code readability.

In Java 9, we can use the diamonda8093152e673feb7aba1828c43532094operator in an anonymous class like below:

Example

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

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

      <strong>Handler<?></strong><!--?--> handler = new <strong>Handler<>("test")</strong> {
         <strong>@Override
</strong>         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

<strong>1
2
test</strong>

The above is the detailed content of How can we use diamond operator with anonymous classes in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete