gpt4 book ai didi

java - 成员级别的匿名内部类

转载 作者:太空宇宙 更新时间:2023-11-04 12:10:11 25 4
gpt4 key购买 nike

《Java OCP 8程序员II学习指南》一书中说

an anonymous inner class is a local inner class

a local inner class is a nested class defined within a method

但是,我可以在方法外部定义匿名内部类:

public class Outer {
Foo ex = new Foo {
@Override
public void bar() {
System.out.println("This is my bar implementation");
}
}
}

void TestClass {
public static void main(String[] args) {
Outer outer = new Outer();
outer.ex.bar();
}
}

这本书说匿名内部类是本地内部类是错误的,因为它不必是本地的(在方法内),还是我提供的示例不是匿名内部类(因为它被分配给命名变量)?

谢谢

最佳答案

ex 不是本地类。本地类不能匿名的任何内容,反之亦然(据我所知)

引用自Oracle's Java OO tutorial on Anonymous Classes :

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

下面几行..

While local classes are class declarations, anonymous classes are expressions, which means that you define the class in another expression

关于java - 成员级别的匿名内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39937905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com