这是我正在尝试的代码;我在“ outer.inner1.inner2 innerobj2 = externalobj.new inner2();”行上遇到错误。
谁能确认嵌套类方法的对象创建错误和语法是什么?
class outer {
public void outerDisplay() {
System.out.println("Statement from outer class");
}
class inner {
public void innerDisplay() {
System.out.println("Statement from inner class");
}
}
class inner1 {
public void inner1Display() {
System.out.println("Statement from inner1 class");
}
class inner2 {
public void inner2Display() {
System.out.println("Statement from inner2 class");
}
}
}
}
public class InnerOuter {
public static void main(String[] args) {
outer outerobj=new outer();
outerobj.outerDisplay();
outer.inner innerobj=outerobj.new inner();
innerobj.innerDisplay();
outer.inner1 innerobj1=outerobj.new inner1();
innerobj1.inner1Display();
**outer.inner1.inner2 innerobj2= outerobj.new inner2()**;
innerobj2.inner2Display();
}
}
最佳答案
类inner2
是inner1
而不是outer
的内部类。
因此,要创建inner2
的实例,您需要这样的inner1
实例:
outer.inner1.inner2 innerobj2= innerobj1.new inner2();
要么
outer.inner1.inner2 innerobj2= outerobj.new inner1().new inner2();