Consider that I have the two following nested classes:
public class Foo {
public class Bar {
}
}
And my goal is to create an instance of class Bar. I've tried to do it the following ways:
// Method one
Foo fooInstance = new Foo();
Foo.Bar barInstance = new fooInstance.Bar // fooInstance cannot be resolved to a type
// Method two
Foo.Bar barInstance = new Foo.Bar(); // No enclosing instance of type Foo is accessible
Any help would be highly appreciated, I'm stuck. As you might notice, I'm a Java-beginner: which doesn't automatically make this a homework question (as a matter of fact - it isn't).
How can one create an instance of the Bar class? Preferably with the same Foo instance.
Close. Instead write:
Foo.Bar barInstance = fooInstance.new Bar();
Here:
Foo.Bar barInstance = new fooInstance.Bar // fooInstance cannot be resolved to a type
you try to instantiate a type that doesn't exist (fooInstance is just a variable)
The right way to do that is, as explained:
Foo.Bar barInstance = new Foo().new Bar()
Here:
Foo.Bar barInstance = new Foo.Bar(); // No enclosing instance of type Foo is accessible
this is valid only for static inner classes of Foo. So, make Boo a static inner class of Foo if this fits your needs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With