Constructor in Java
Constructor is a special method in java. Constructor name must be same as class name and constructor do not have any return type but constructor may have any access specification level such as public private etc. Constructor in java cannot be abstract , static , final or synchronized. These Modifiers are not allowed for constructor in java. Unlike C++ there is no destructor in java.
Constructors are of two types; default constructor & user defined Constructor or parameterized Constructor. Constructors are called automatically while creating the object of a class or we do not need call the constructor e.g. we call the simple method through class reference.
The Constructor support by JVM is called as “Default Constructor” and all constructor defined by user is called as “User-Defined Constructor”. In Java every class has a constructor i.e. called as default constructor. In java Constructor can be overloaded.
We use two keyword for calling constructor or accessing data member of constructor i.e. “Super” and “this”.
Note:- “this” keyword is used for calling current class instances and “super ” keyword is used for calling parent class instances.
Example:-1
package Demo;
class test {
int p;
public test() //default constructor
{
// TODO Auto-generated constructor stub
p=0;
}
test(int x) //paremetrized Contructor
{
// TODO Auto-generated constructor stub
p=x;
}
public void display()
{
System.out.println(p);
}
}
class constr
{
public static void main(String args[])
{
test t=new test(); //its called default constructor
test t1=new test(10); //its called parameterized constructor
t.display();
t1.display();
}
}
Output:-
0
10
Example:-2
package Demo;
class test {
public test() //default constructor
{
// TODO Auto-generated constructor stub
System.out.println(“Hello”);
}
}
class constr extends test
{
public constr() {
// TODO Auto-generated constructor stub
System.out.println(“Hii”);
}
public static void main(String args[])
{
constr t=new constr(); //its called default constructor
}
}
Output:-
Hello
Hii
Explanation:-
In the example 2 the parent class constructor is executed because we extends the test class in constr class , all the properties of test class inherits in constr class and JVM firstly goes to the default constructor of the class.