Home > Java > javaTutorial > 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
Release: 2023-08-27 09:13:02
forward
739 people have browsed it

在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 diamond<>operator 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();
}
Copy after login

Output

<strong>1
2
test</strong>
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template