Home » Core Java » Constructor in Java

Constructor in Java


Constructor in Java is not an ordinary method but a special method used to initialize the object.JVM invokes the constructor, and invokes it immediately after creating an object using new keyword.
Suppose there is a class Employee.
So, when you write Employee instance = new Employee();
The constructor of Employee class is invoked by JVM as soon as its object is created using new operator.

Rules :
Let’s see what are the rules constructor obeys.
1 : Constructor name must be same as Class name.
2 : Constructor must have no explicit return type.But constructor internally returns the instance or object of the class.

Types of Constructor :
Constructor are basically of 2 types.
1. Default constructor (no-arg constructor)
2. Parameterized constructor

1. Default constructor (no-arg constructor) :
If there is no constructor defined in a class then compiler automatically creates a default constructor.So its scope
will be default.It will assign default values to objects like 0 for integer null for String etc.So based on type of object ,default values will be assigned.

Parameterized constructor :
A constructor that have parameters or arguments is known as parameterized constructor.By providing distinct set of values in parameterized constructor,we get different objects with different values

Constructor  Overloading :
If a class have more than one constructors that differ in parameter lists and parameter types,then it is called constructor overloading.It is similar to method overloading.

Constructor  Chaining :
1 : Calling one constructor inside another constructor in Java is called Constructor chaining.
2 : For calling constructor of same class use this keyword and  and calling constructor of super class use super keyword.
3 : Constructor call must be the first statement in a constructor otherwise you will get compile time error.

Constructor in Java can not be abstract, static, final or synchronized :
1 : Constructor can’t be overridden and abstract needs overriding ,so there is no use to have abstract constructor.
2 : Constructor is called when an instance of the class is created, it has access to instance fields of the class or object level property of a class.There is no use to have static constructor.
3 : Constructors aren’t inherited so can’t be overridden ,so there is no use to have final constructor.
4 : synchronized means that actions on the same object can not be performed by multiple threads i.e. object is locked by one thread and when the constructor is called  by other thread ,you still don’t have the object. So,It is logically impossible for two threads to access the constructor of the same object.

Leave a comment

Your email address will not be published. Required fields are marked *

five + 5 =