Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating instance of class within class

Tags:

java

oop

class

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.

like image 421
Zar Avatar asked Jun 01 '26 04:06

Zar


2 Answers

Close. Instead write:

Foo.Bar barInstance = fooInstance.new Bar();
like image 112
Paul Bellora Avatar answered Jun 03 '26 16:06

Paul Bellora


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

like image 33
Razvan Avatar answered Jun 03 '26 17:06

Razvan