本文介绍了外层阶级呼唤内层阶级的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道要实例化一个成员内部类,您有两个不同的构造函数:
I know that to instantiate a member inner class, you have two different constructors:
第一:
Outer out = new Outer();
Outer.Inner in = out.new Inner();
第二:
Outer.Inner in = new Outer().new Inner();
现在,我不知道为什么编译此代码:
Now, I don't know why this code compiles:
public class Outer {
private String greeting="Hi";
protected class Inner {
public int repeat=3;
public void go() {
for (int i =0; i<repeat; i++) {
System.out.println(greeting);
}
}
}
public void callInner() {
Inner in = new Inner(); //in my opinion the correct constructor is Outer.Inner in = new Inner()
in.go();
}
public static void main(String[] args) {
Outer out = new Outer();
out.callInner();
}
}
为什么要编译?
非常感谢!
推荐答案
在外部
范围内(实例方法内部)实例化 Inner
时,您会执行无需像在您的示例中那样显式实例化引用外部
类别:
As you are instantiating Inner
within the scope of Outer
(inside an instance method), you do not need to explicitly instantiate referencing the Outer
clas, like in your example:
Outer.Inner in = new Outer().new Inner();
仅引用 Inner
即可实例化:
Inner in = new Inner();
这适用于类中的所有实例方法,只要它们不是静态的.
This applies to all instance methods within a class, as long as they are not static.
这篇关于外层阶级呼唤内层阶级的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!