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

Is it possible to create an object of an inner class in the constructor of an outer class?

0
source share
3 answers

Of course.

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

    class Inner
    {
    }
}
+6
source

Yes, it is legal to build an inner class in the constructor of the outer class. For instance:

public class Outer {
    private Inner myInner;

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

    public class Inner {

    }
}

Read the Sun Nested Classes Tutorial .

+1
source

If I understand you correctly, then yes, if you use composition.

Psudeo-code example:

public class Inner(){
  //code
}

public class Outer(){
   Inner foo;

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

}
-1
source

All Articles