gpt4 book ai didi

java - ParentClass.NestedClass 是否 nc= new NestedClass();隐式实例化父类实例?

转载 作者:搜寻专家 更新时间:2023-11-01 02:01:28 26 4
gpt4 key购买 nike

我有课本上的代码:

public class Question_3_4 {
public static class Inner {
private void doIt() {
System.out.println("doIt()");
}
}
public static void main(String[] args) {
Question_3_4.Inner i = new Inner();
i.doIt();
}
}

好吧,内部类是静态的,所以我假设上面的代码隐式实例化了 Question_3_4 的实例?

Question_3_4.Inner i = new Question_3_4.Inner();

产生与上述代码相同的结果。

所以我认为

  Question_3_4.Inner i = new Question_3_4.Inner();   

  Question_3_4.Inner i = new Inner();

是同一件事。

如果我的假设是错误的,我在这里遗漏了什么?

最佳答案

首先,您没有使用正确的术语。

你没有声明一个内部类,而是一个静态嵌套类。

Terminology: Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes.

您可以获得有关术语以及如何以及为何在 Java Oracle Nested Classes tutorial 上使用嵌套类的可访问且有用的信息:

关于你的问题:

Well, Inner class is static, so I assume the above code implicitly instantiates Question_3_4's instance ?

你不需要实例化外部类来实例化一个嵌套类或者也可以说是一个static嵌套类。
此外,如果需要,编译器不会为您实例化外部类,而是会发出编译错误。

仅在内部类的情况下才需要实例化外部类(没有 static 嵌套类)。

例如,删除嵌套类的 static 修饰符,将根据需要为 Question_3_4.Inner i = new Inner(); 行产生编译错误有一个外部类的实例被实例化。

public class Question_3_4 {

public class Inner {
private void doIt() {
System.out.println("doIt()");
}
}
public static void main(String[] args) {
Question_3_4.Inner i = new Inner();
^--- error: non-static variable this cannot be referenced from a static context
i.doIt();
}

}

关于java - ParentClass.NestedClass 是否 nc= new NestedClass();隐式实例化父类实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45499143/

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