Home > Java > javaTutorial > body text

How to create anonymous inner classes in Java?

WBOY
Release: 2024-05-01 08:39:01
Original
391 people have browsed it

Anonymous inner classes are inner classes defined when creating an instance without an explicit name. Syntax: new () { // 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 <基类或接口名>() {
    // 匿名内部类体
};
Copy after login

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();
Copy after login

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);
Copy after login

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!

source:php.cn
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