See the Tutorial List

Constructors in Java

A constructor is a special method that is used to initialize an object.Every class has a constructor,if we don't explicitly declare a constructor for any java class the compiler builds a default constructor for that class. A constructor does not have any return type.

A constructor has same name as the class in which it resides. Constructor in Java can not be abstract, static, final or synchronized. These modifiers are not allowed for constructor.

class Car
{
 String name ;
 String model;
 Car( )    //Constructor
 {
  name ="";
  model="";
 }
}

Types of Constructor

There are 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. There can be two types of constructor i.e System Define default constructor or user defines default constructor. If a class does not contain any constructor then during compilation the system 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

default-constructor

User Define Default Constructor

Example:

  
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();  
  }  
}  
  

default-constructor

System Define default constructor

Example:

  
class AddDemo1
{  
  public static void main(String args[])
  {  
    AddDemo1 obj=new AddDemo1();  
  }  
}  
  

system-constructor

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 in Java.


Q. Why do we Overload constructors?

Constuctor overloading is done to construct object in different ways.


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


Q What's the difference between constructors and normal methods?

Constructors must have the same name as the class and can not return a value. They are only called once for a single object while regular methods could be called many times and it can return a value or can be void.


Q. What is constructor chaining in Java?

Constructor chaining is a phenomena of calling one constructor from another constructor of same class. Since constructor can only be called from another constructor in Java, constructor chaining is used for this purpose.

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

In Java, Constructor chaining is a process in which one constructor is called from another constructor. The constructor chaining can be done in two ways i.e within the same class and from the base class. Within the same class can be done using this() keyword and from the base class can be done using super() keyword. The concept of inheritance is used in constructor chaining. Constructor chaining is used when we want to perform multiple tasks in a single constructor.

constructor-chaining

Example:

  
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();
  }
}
  

output-constructor-chaining


Assigning values to static final variables in Java

In Java, when a variable is non-static and final then the value can be assigned in the constructor or at the time of declaration the variable. But when a static final variable is declared it can not be assigned value in the constructor. It can only be assigned value at the time of declaration.

Example:

  
class AddDemo2{ 
    final inti; 
    AddDemo2() 
    { 
i = 10;
  System.out.println("The Value of i = "+i); 
    } 
    public static void main(String args[])
    {  
  AddDemo2 obj=new AddDemo2();  
    }  

}
  

assign-value-to-static-variable

Example 2:

  
class AddDemo2{ 
    static final inti; 
    static
    {
  i=10; 
    }
    AddDemo2() 
    { 
  System.out.println("The Value of i = "+i); 
    } 
    public static void main(String args[])
    {  
  AddDemo2 obj=new AddDemo2();  
    }  
}
  

assign-value-to-static-variable

Copy Constructor

In Java, to Create a Copy constructor, one object is copied to another object. Arguments of copy constructor must object. There can be two types of copy constructor i.e System Define or user defines. A system provides its own copy constructor if no copy constructor is defined.

Example:

  
class pnb
{
  private intsa;
  public pnb()
  {}
  public pnb(int x)
  {
    sa=x;
  }
  public pnb(pnb x)
  {
    this.sa=x.sa;
  }
  public void display()
  {
    System.out.println("Saving Account = "+sa);
  }
}
class CopyDemo1
{
  public static void main(String as[])
  {
    pnbobj = new pnb(2000);
    pnb obj1 = new pnb(obj);
    pnb obj2 = new pnb();
    
    System.out.println("object ");
    obj.display();
    System.out.println("object 1");
    obj1.display();
    System.out.println("object 2");
    obj2.display();
    
    System.out.println("System provide its own copy constructor ==> object 2");
    obj2=obj;
    obj2.display();
  }
}
  

copy-constructor

Private Constructors

In Java, private constructors are used in 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 constructor. A class which have a private constructor and all the methods are static then it is class 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);
  }
}
  

private-constructor

Q. Does constructors return any value?

Yes, constructors return current instant of a class. But yet constructor signature cannot have any return type.


Singleton Class

In Java, a Singleton class is used when we want to create only one object at a time. To create a singleton class we have to create a private constructor and methods of the class should be static. The concept of Lazy initialization is used for creating a static method. The main difference between a normal class and a singleton class is that in normal class we use constructor and in singleton class, we use getInstance() method. The getInstance() method creates an object with the name of the class.

Below is an example using getInstance() method

Example:

  
class Demo1
{ 
    private static Demo1 a = null; 
    public String s;  
    private Demo1() 
    { 
        s = "Hello Welcome to studytonight.com. You are Reading about Singleton class"; 
    } 
    public static Demo1 getInstance() 
    { 
        if (a== null) 
            a = new Demo1(); 
        return a; 
    } 
} 

class SingletonDemo1
{ 
    public static void main(String args[]) 
    { 
        Demo1 p = Demo1.getInstance(); 
        Demo1 q = Demo1.getInstance(); 
        Demo1 r = Demo1.getInstance(); 
p.s = (p.s).toUpperCase(); 
System.out.println("String from p is " + p.s); 
System.out.println("String from q is " + q.s); 
System.out.println("String from r is " + r.s); 
System.out.println("\n"); 
r.s = (r.s).toLowerCase(); 
System.out.println("String from p is " + p.s); 
System.out.println("String from q is " + q.s); 
System.out.println("String from r is " + r.s); 
    } 
}
  

singleton-class

Below is an example, in which a singleton class is created and the name of methods is the same as of class.

Example:

  
class Demo1
{ 
    private static Demo1 a = null; 
    public String s;  
    private Demo1() 
    { 
        s = "Hello Welcome to studytonight.com. You are Reading about Singleton class"; 
    } 
    public static Demo1 Singleton() 
    { 
        if (a== null) 
            a = new Demo1(); 
        return a; 
    } 
} 

class SingletonDemo1
{ 
    public static void main(String args[]) 
    { 
        Demo1 p = Demo1.Singleton(); 
        Demo1 q = Demo1.Singleton(); 
        Demo1 r = Demo1.Singleton(); 
p.s = (p.s).toUpperCase(); 
System.out.println("String from p is " + p.s); 
System.out.println("String from q is " + q.s); 
System.out.println("String from r is " + r.s); 
System.out.println("\n"); 
r.s = (r.s).toLowerCase(); 
System.out.println("String from p is " + p.s); 
System.out.println("String from q is " + q.s); 
System.out.println("String from r is " + r.s); 
    } 
}
  

singleton-class-demo