0

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?

1
  • Employee emp= new Class1().new Employee(); Commented Dec 14, 2014 at 1:56

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

3
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();

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.