Creating an Instance of a Java Class
- javastrokes
- Sep 27, 2016
- 2 min read
In Java all the objects are constructed. When you make an object for a class type, at least one constructor should be invoked. Either default constructor or parameterized constructor. Default constructor is the constructor which takes no arguments. Constructors are used to initialize an object of your class type and they don’t have returntype. Check out previous post for “Java Class Declartion” for declaring classes.
Creating an Instance of a Java Class by using ‘default’ & parameterized constructors:

Syntax to create an object or an instance of a class:
new <<Call to Class Constructor>>;
Here, the “new” operator is followed by a call to the constructor of the class whose instance is being created. The new operator will create an object of a class by allocating the memory on heap. When an object or instance of a class is created, memory is allocated for instance variables such as employeeName and employeeId.
Note: class variables are not allocated memory when an instance of the class is created.
Check out previous post titled “Java Class Declaration” for instance and static variable declarations. Check the example given below, which creates an instance of the Employee class:
new Employee();
Now, an object for an Employee class is created by calling the default constructor of Employee class, which initializes the fields of an object of Employee class type. This constructor sets the default values to the fields of Employee object.
new Employee(102, “Cory”);
Again, an object for an Employee class is created by calling the parameterized constructor of Employee class, which initializes the fields of an object of Employee class type by using the values passed to its parameters. The name of a class defines a new reference type in Java. A variable of a specific reference type can store the reference of an instance or object of the same reference type in memory.
Here, the below reference variable, which will store a reference of an object of the Employee class. You can declare the variable as shown:
Employee emp;
‘emp’ is reference variable and the type of the variable is ‘Employee’. Now, the ‘emp’ variable can be used to store a reference of an instance of the Employee class.
emp = new Employee();
The reference to an object of type “Employee” class is stored in a reference variable ‘emp’.
Comments