Home  >  Article  >  Java  >  How to create anonymous inner classes in Java?

How to create anonymous inner classes in Java?

WBOY
WBOYOriginal
2024-05-01 08:39:01371browse

Anonymous inner classes are inner classes defined when creating an instance without an explicit name. Syntax: new 6fbafa35b4f73740ce9fc2c7d0dbbcca() { // Anonymous inner class body}. Advantages: simplicity, code reuse, local scope. Disadvantages: poor readability and difficulty in debugging. Practical examples include overriding anonymous classes and implementing anonymous interfaces.

Java 匿名内部类如何创建?

Java Anonymous Inner Class Creation Guide

What is an anonymous inner class?

Anonymous inner class is an inner class defined when creating an instance. They have no explicit name and are often used to override or implement a class or interface on a short notice.

Creating anonymous inner classes

To create anonymous inner classes in Java, use the following syntax:

new <基类或接口名>() {
    // 匿名内部类体
};

The base class or interface name is anonymous A class or interface from which an inner class will inherit or implement. The class body contains the definitions of the methods and fields of the anonymous inner class.

Practical case

1. Override anonymous class

Use anonymous inner class to override Runnable class The run() method:

Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("匿名内部类线程运行");
    }
});

thread.start();

2. Implement the anonymous interface

Use the anonymous inner class to implement the Comparator interface:

List<String> strings = new ArrayList<>();

Comparator<String> comparator = new Comparator<>() {
    @Override
    public int compare(String s1, String s2) {
        return s1.length() - s2.length();
    }
};

strings.sort(comparator);

Advantages

  • Simplicity: Anonymous inner classes can be created directly without defining a separate class file.
  • Code Reuse: They can be used to create temporary implementations that are used only once.
  • Local scope: Anonymous inner classes can only be accessed within the scope of the class or method that created them.

Disadvantages

  • Readability: Anonymous inner classes can make code difficult to read and understand.
  • Debugging Difficulty: Because anonymous inner classes do not have names, they may be more difficult to track when debugging.

The above is the detailed content of How to create anonymous inner classes in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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