Constructors in Java
A constructor is a special method that is used to initialize an object. Every class has a constructor either implicitly or explicitly.
If we don't declare a constructor in the class then JVM builds a default constructor for that class. This is known as default constructor.
A constructor has same name as the class name in which it is declared. Constructor must have no explicit return type. Constructor in Java can not be abstract, static, final or synchronized. These modifiers are not allowed for constructor.
Syntax to declare constructor
className (parameter-list){
code-statements
}
className is the name of class, as constructor name is same as class name.
parameter-list is optional, because constructors can be parameterize and non-parameterize as well.
Constructor Example
In Java, constructor structurally looks like given in below program. A Car class has a constructor that provides values to instance variables.
class Car
{
String name ;
String model;
Car( ) //Constructor
{
name ="";
model="";
}
}
Types of Constructor
Java Supports two types of constructors:
- Default Constructor
- Parameterized constructor
Each time a new object is created at least one constructor will be invoked.
Car c = new Car() //Default constructor invoked
Car c = new Car(name); //Parameterized constructor invoked
Default Constructor
In Java, a constructor is said to be default constructor if it does not have any parameter. Default constructor can be either user defined or provided by JVM.
If a class does not contain any constructor then during runtime JVM generates a default constructor which is known as system define default constructor.
If a class contain a constructor with no parameter then it is known as default constructor defined by user. In this case JVM does not create default constructor.
The purpose of creating constructor is to initialize states of an object.
The below image shows how JVM adds a constructor to the class during runtime.
User Define Default Constructor
Constructor which is defined in the class by the programmer is known as user-defined default constructor.
Example:
In this example, we are creating a constructor that has same name as the class name.
class AddDemo1
{
AddDemo1()
{
int a=10;
int b=5;
int c;
c=a+b;
System.out.println("*****Default Constructor*****");
System.out.println("Total of 10 + 5 = "+c);
}
public static void main(String args[])
{
AddDemo1 obj=new AddDemo1();
}
}
Constructor Overloading
Like methods, a constructor can also be overloaded. Overloaded constructors are differentiated on the basis of their type of parameters or number of parameters. Constructor overloading is not much different than method overloading. In case of method overloading you have multiple methods with same name but different signature, whereas in Constructor overloading you have multiple constructor with different signature but only difference is that constructor doesn't have return type.
Example of constructor overloading
class Cricketer
{
String name;
String team;
int age;
Cricketer () //default constructor.
{
name ="";
team ="";
age = 0;
}
Cricketer(String n, String t, int a) //constructor overloaded
{
name = n;
team = t;
age = a;
}
Cricketer (Cricketer ckt) //constructor similar to copy constructor of c++
{
name = ckt.name;
team = ckt.team;
age = ckt.age;
}
public String toString()
{
return "this is " + name + " of "+team;
}
}
Class test:
{
public static void main (String[] args)
{
Cricketer c1 = new Cricketer();
Cricketer c2 = new Cricketer("sachin", "India", 32);
Cricketer c3 = new Cricketer(c2 );
System.out.println(c2);
System.out.println(c3);
c1.name = "Virat";
c1.team= "India";
c1.age = 32;
System .out. print in (c1);
}
}
this is sachin of india
this is sachin of india
this is virat of india
Constructor Chaining
Constructor chaining is a process of calling one constructor from another constructor in the same class. Since constructor can only be called from another constructor, constructor chaining is used for this purpose.
To call constructor from another constructor this keyword is used. This keyword is used to refer current object.
Lets see an example to understand constructor chaining.
class Test
{
Test()
{
this(10);
}
Test(int x)
{
System.out.println("x="+x);
}
public static void main(String arg[])
{
Test object = new Test();
}
}
x=10
Constructor chaining is used when we want to perform multiple tasks by creating a single object of the class.
In the below image, we have described the flow of constructor calling in the same class.
Example:
Lets see one more example to understand the constructor chaining. Here we have created three constructors and calling them using by using this keyword.
class abc
{
public abc()
{
this(5);
System.out.println("Default Constructor");
}
public abc(int x)
{
this(5, 6);
System.out.println("Constructor with one Parameter");
System.out.println("Value of x ==> "+x);
}
public abc(int x, int y)
{
System.out.println("Constructor with two Parameter");
System.out.println("Value of x and y ==> "+x+" "+y);
}
}
class ChainingDemo1
{
public static void main(String as[])
{
abcobj = new abc();
}
}
Private Constructors
In Java, we can create private constructor to prevent class being instantiate. It means by declaring a private constructor, it restricts to create object of that class.
Private constructors are used to create singleton class. A class which can have only single object known as singleton class.
In private constructor, only one object can be created and the object is created within the class and also all the methods are static. An object can not be created if a private constructor is present inside a class. A class which have a private constructor and all the methods are static then it is called Utility class.
Example:
final class abc
{
private abc()
{}
public static void add(int a, int b)
{
int z = a+b;
System.out.println("Addition: "+z);
}
public static void sub(int x, int y)
{
int z = x-y;
System.out.println("Subtraction: "+z);
}
}
class PrivateConDemo
{
public static void main(String as[])
{
abc.add(4, 5);
abc.sub(5, 3);
}
}