Home  >  Article  >  Java  >  What is the life cycle of Java anonymous inner classes?

What is the life cycle of Java anonymous inner classes?

王林
王林Original
2024-05-01 16:06:01945browse

The life cycle of an anonymous inner class is determined by its scope: method-local inner class: only valid within the scope of the method that created it. Constructor inner class: bound to the outer class instance and released when the outer class instance is released. Static inner classes: loaded and unloaded at the same time as external classes.

Java 匿名内部类的生命周期是怎样的?

The life cycle of Java anonymous inner classes

After an anonymous inner class is created, its life cycle is mainly affected by its scope. Effects:

  • Method local inner class: Valid only within the scope of the method that created it. When the method exits, the inner class and all its members are released.
  • Constructor inner class: After creating an external class instance, the constructor inner class will take effect. When the outer class instance is released, the inner class is also released.
  • Static inner class: Static inner class and external class are loaded at the same time. When the outer class is unloaded, the static inner class is also unloaded.

Practical case:

Create an anonymous inner class implementation Comparable Interface:

List<Integer> numbers = new ArrayList<>();

// 创建匿名内部类比较器
Comparator<Integer> comparator = new Comparator<Integer>() {
    @Override
    public int compare(Integer a, Integer b) {
        return a - b;
    }
};

// 根据比较器排序列表
Collections.sort(numbers, comparator);

In this example, Anonymous inner class comparator used to sort a list of numbers. Since comparator is a local inner class, it can only be used within the scope of the method that created it. When the sort method is completed, comparator will also be released.

The above is the detailed content of What is the life cycle of Java anonymous inner classes?. 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