Reputation: 13
Currently learning about inner class. I have two classes. In second class there is an inner class. I am trying to create an object of the inner class in the second class. But I am getting compilation error. Can anyone help?
Here is my code:
public class MainClass {
public static void main(String[] args) {
NestedClass.NewUser newUserObj = new NewUser("User");
System.out.println(newUserObj.Name);
}
}
class NestedClass {
class NewUser {
public String Name;
NewUser(String name) {
this.Name = name;
}
}
}
Upvotes: 1
Views: 146
Reputation: 128829
Alternate option: make the inner class static
. Then, technically, it's no longer an "inner" class but only a "nested" class, and you can instantiate it with new NestedClass.NewUser()
. As explained in the Nested Classes Tutorial, static nested classes can be instantiated without having an instance of the enclosing class, like the other answers refer to.
Upvotes: 2
Reputation: 159784
Despite the name NestedClass
is not a nested class but rather an outer class, so an instance of NestedClass
is required to create an instance of the real nested class, i.e. NewUser
NestedClass.NewUser newUserObj = new NestedClass().new NewUser("User");
Upvotes: 2
Reputation: 279970
You can only create an instance of NewUser
with an instance of NestedClass
.
new NestedClass().new NewUser("User");
Upvotes: 2
Reputation: 15553
To instantiate an inner class, you must first instantiate the outer class.
Create the inner object using the outer object as shown below:
NestedClass.NewUser newUserObj = (new NestedClass()).new NewUser("User");
Reference: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Upvotes: 6