tags:

views:

139

answers:

3

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

A: 

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

}
GSto
+6  A: 

Sure.

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

    class Inner
    {
    }
}
Jonathan Feinberg
+1  A: 

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.

Ally Sutherland