为内部类(嵌套类内的类)创建对象时出错

时间:2019-03-19 20:29:48

标签: java inner-classes

这是我正在尝试的代码;我在“ 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();      
  }
}

1 个答案:

答案 0 :(得分:2)

inner2inner1而不是outer的内部类。 因此,要创建inner2的实例,您需要像这样的inner1的实例:

outer.inner1.inner2 innerobj2= innerobj1.new inner2();

outer.inner1.inner2 innerobj2= outerobj.new inner1().new inner2();