clankill3r
clankill3r

Reputation: 9543

create instance of enclosing class

Let's say I have this structure:

  public class Foo {

        public class Bar {

        }

    }

Now how can I create an instance of Bar after creating a Foo? Something like this but not this:

 Foo foo = new Foo();
 Foo.Bar bar = new foo.Bar();

Upvotes: 1

Views: 479

Answers (4)

B B
B B

Reputation: 1950

Foo fooInstance = new Foo();
Foo.Bar barInstance = fooInstance.new Bar(); 

Upvotes: 1

Neeraj Jain
Neeraj Jain

Reputation: 7730

There are 2 ways to achieve

keep your inner class non static

class Foo   
{
  ...
  class Bar
  {
   ...
  }
}
 //then 
Foo foo = new Foo();
Foo.Bar car = foo.new Bar();

Make you inner class static

public class Foo {
  public static class Bar {
  }
}
public class Test {
...
  Foo.Bar bar = new Foo.Bar();

}

Upvotes: 0

sarveshseri
sarveshseri

Reputation: 13985

You need to make your inner class static, so that you can reference to it without creating an instance of outer class.

public class Foo {

    public static class Bar {

    }

}

Now you can reference to Bar without creating an instance of Foo,

Foo.Bar bar = new Foo.Bar();

Upvotes: 0

Florent Bayle
Florent Bayle

Reputation: 11920

You are nearly there:

Foo foo = new Foo();
Foo.Bar bar = foo.new Bar();

Upvotes: 2

Related Questions