简体   繁体   中英

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

我们可以在外部类的构造函数中创建内部类的对象吗?

Sure.

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

    class Inner
    {
    }
}

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 .

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();
   }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM