gpt4 book ai didi

java - 内部类中的静态方法错误

转载 作者:行者123 更新时间:2023-12-01 18:32:35 25 4
gpt4 key购买 nike

我试图了解内部类的工作原理,在尝试一些简单的代码时出现错误:The method hello cannot be declared static; static methods can only be declared in a static or top level type

在这段代码上

public class Class1 {
public static void main(String[] args) {
Class1 c = new Class1();
c.show();
}

public static void show() {
class C2 {

static public void hello() {
System.out.println("show class");
}
}

C2.hello();
}

}

我不明白为什么!

最佳答案

请参阅documentation here .

内部类:与实例方法和变量一样,内部类与其封闭类的实例相关联,并且可以直接访问该对象的方法和字段。另外,由于内部类与实例关联,因此它本身不能定义任何静态成员。

关于java - 内部类中的静态方法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23469099/

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