2

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.

4 Answers 4

4

Close. Instead write:

Foo.Bar barInstance = fooInstance.new Bar();
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

2

You have to create object of inner class like :

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

If inner class is static, then you can create them directly as :

public class Foo {    
    static public class Bar {    
    }    
} 


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

1 Comment

+1 for making the inner class static if you can. Instantiating a non-static inner class from outside the containing class may indicate a problem with your design.
0

It should be

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.