kitty ahuja
kitty ahuja

Reputation: 1

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

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

Upvotes: 0

Views: 2031

Answers (3)

Alistair Sutherland
Alistair Sutherland

Reputation: 1361

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.

Upvotes: 1

Jonathan Feinberg
Jonathan Feinberg

Reputation: 45364

Sure.

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

    class Inner
    {
    }
}

Upvotes: 6

GSto
GSto

Reputation: 42380

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

}

Upvotes: -1

Related Questions