Reputation: 16629
I have
class Class1{
public class Employee{
}
public static void Main(String[] args){
Class1 c = new Class1();
// Create instance of Employee Class
}
}
How to create instance of class Employee?
Upvotes: 0
Views: 5356
Reputation: 3105
Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:
class OuterClass {
...
class InnerClass {
...
}
}
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
ref :Doc Oracle
Upvotes: 4
Reputation: 894
class Class1 {
public class Employee {
}
public static void Main(String[] args){
Class1 c = new Class1();
Employee e = c.new Employee();
// Create instance of Employee Class
}
}
You do need the instance of the superclass to instanciate an Employee, because Employee is a non static Subclass of Class1.
Otherwise add the static keyword to Employee like this
public static class Employee {
}
to be able to instanciate an Employee without an instance of Class1, which would then look like this:
Employee e = new Class1.Employee();
Upvotes: 3