【问题标题】:Why can't an anonymous class have static members (other than final ones) in Java?为什么匿名类在 Java 中不能有静态成员(最终成员除外)?
【发布时间】:2020-10-04 15:24:34
【问题描述】:

Anonymous classes cannot have any static members except for those that are constant. 静态成员属于一个类而不是单个实例。因此,匿名类中应该允许静态成员,因为该类不能有多个实例。

【问题讨论】:

  • 所以根据你的断言“类不能有多个实例”,那么在这种情况下,static 需要什么?
  • 除了编译时常量之外,匿名类不允许使用静态成员,它们的值被有效地内联到编译的代码中,因此它们根本不存在。

标签: java anonymous-class


【解决方案1】:

as the class cannot have multiple instances.

肯定可以的!

活生生的例子:

import java.util.ArrayList;
import java.util.List;

public class AnonymousTest {

    public static void main(String[] args) {
        List<Runnable> runnables = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            final int id = i;
            runnables.add(new Runnable() {
                @Override
                public void run() {
                    System.out.println("Hello ! " + id);
                }
            });
        }
        runnables.forEach(System.out::println);
    }
}

输出:

AnonymousTest$1@58372a00
AnonymousTest$1@4dd8dc3
AnonymousTest$1@6d03e736

如您所见,AnonymousTest 可以有很多实例!这里我们有三个不同的。

匿名类的一个限制是它们必须在创建它们的实例的生命周期之后存在。所以,他们需要复制所有外部变量,这就是为什么你需要它们 final。

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多