Java - Creating Instances of a Class


The following is the general syntax to create an instance of a class:

new <Call to Class Constructor>;

The new operator is followed by a call to the constructor of the class. It creates an instance of a class by allocating the memory on heap.


The following statement creates an instance of the Employee class:

new Employee();

Here is the definition of Employee class

class Employee {
        String name;        // An instance variable
        String gender;      // An instance variable
        static long count;  // A class variable because of the static modifier

Employee() is a call to the constructor of the Employee class.

The name of the constructor is the same as the class name.

When you do not add a constructor to a class, the Java compiler adds a default constructor for you.

The default constructor accepts no arguments.

Related Topic