Reputation: 9543
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
Reputation: 1950
Foo fooInstance = new Foo();
Foo.Bar barInstance = fooInstance.new Bar();
Upvotes: 1
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
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
Reputation: 11920
You are nearly there:
Foo foo = new Foo();
Foo.Bar bar = foo.new Bar();
Upvotes: 2