Constructor: Constructor is special method of class that is automatically invoked whenever the object is created. It is used to initialize the member variables of object.
Rules to create constructor
- Constructor name should exactly match with class name.
- Access specifier of constructor could be private/public or protected.
- Constructor should not have any return type not even void.
- Constructor should not contain any return statement.
- Overloading of constructor is allowed.
- Implicit return value of constructor is always an object.
Types of constructor
There are only two types of constructor available in java language as given below.
- Default Constructor: Constructor with no parameter or zero parameters is known as default constructor.
- Parameterized Constructor: Constructor with one or more than one parameters is known as parameterized constructor.
Note: copy constructor is not available in java language, but we can perform operation of copy constructor using the parameterized constructor.
private int a;
public Data(int n)
public void show()
public static void main(String args)
Data d1=new Data();
Data d2=new Data(100);
In the above example, Data class contain two types of constructor i.e. default and parameterized constructor. Default constructor is initializing the value of member variable ‘a’ by 10 where as parameterized constructor is initializing the value of member variable by the value of given parameter.
During the execution of main program, object d1 will create memory and initialize the value of member variable by executing the default constructor where as object d2 will create memory and initialize the value of member variable by using parameterized constructor.
Note: if constructors are defined in the class then we can access only the defined constructors but if the class is not containing any constructor then we can access default constructor.