Can we create an object of the inner class in the constructor of the outer class?

冷暖自知 提交于 2019-12-11 14:02:44

问题


Can we create an object of the inner class in the constructor of the outer class?


回答1:


Sure.

public class Outer
{
    public Outer()
    {
        Inner inner = new Inner();
    }

    class Inner
    {
    }
}



回答2:


Yes it's legal to construct an inner class in constructor of outer class. For example:

public class Outer {
    private Inner myInner;

    public Outer() {
        myInner = new Inner();
    }

    public class Inner {

    }
}

Have a read through the Sun Nested Classes Tutorial.




回答3:


If I understand you correctly, then yes, if your using composition.

psudeo-code example:

public class Inner(){
  //code
}

public class Outer(){
   Inner foo;

   public Outer() {
      this.foo = new Inner();
   }

}


来源:https://stackoverflow.com/questions/2208012/can-we-create-an-object-of-the-inner-class-in-the-constructor-of-the-outer-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!