Home » Java » Constructor in Java

Constructor in Java

Constructor in Java is block of code which will be used to initialize an object. It looks like a method, however it is not a method. Methods have return type but constructors don’t have any return type.

Constructors gets called when an object is instantiated. In other words, when you use the new keyword for creating the object of the class. For example. Employee obj = new Employee(); (here Employee() is a default constructor of Employee class).

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.


Java Constructor Example


class Student {
  //constructor
  Student() {
    System.out.println("Constructor  called.");
  }
  public static void main(String[] args) {
    Student object = new Student(); //creating object
  }
}

Output :

Constructor  called.

This code is the simplest example of constructor, we created class Student and create an object, constructor is called when object is created. As you can see in output "Constructor called." is printed.


RULES/PROPERTIES/CHARACTERISTICS of a constructor :

  • Constructor name must be similar to name of the class.
  • Constructor should not return any value even void also (if we write the return type for the constructor then that constructor will be treated as ordinary method).
  • Constructors should not be static since constructors will be called each and every time whenever an object is creating.
  • Constructors will not be inherited.
  • Constructors are called automatically whenever an object is created.

Types of java Constructors

There are two types of constructors.

  • Default Constructor (no-arg constructor)
  • Parametrized Constructor

Java Default Constructor

A constructor that have no parameter is known as default constructor.

Default constructor provides the default values to the object like 0, null etc. depending on the type.

Defining the default constructor in a class is optional. If we are not defining constructor in a class, compiler automatically creates a default constructor. If we define, JVM will call user/programmer defined default constructor.

Syntax of default constructor :


class 
{
classname () //default constructor
{
Block of statements;
………………………………;
………………………………;
}
………………………;
………………………;
}

Example of default Constructor

In this example, we are creating the no-arg constructor in Student class. This Constructor will be invoked at the time of object creation.


class Student{  
Student(){
System.out.println("Student Class default Constructor");
}  
public static void main(String args[]){  
Student s=new Student();  
}  
}  

Output :


Student Class default Constructor

Java parametrized constructor

A parametrized constructor is one which takes some parameters.Parametrized constructor will be used to provide different values to the objects.


Example of parametrized constructor


class Student{  
    int id;  
    String name;  
      
    Student(int i,String n){  
    id = i;  
    name = n;  
    }  
    void display(){System.out.println(id+" "+name);}  
   
    public static void main(String args[]){  
    Student s1 = new Student(10,"Mukesh");  
    Student s2 = new Student(20,"Raj");  
    s1.display();  
    s2.display();  
   }  
}  

Output :


10 Mukesh
20 Raj

Whenever we create an object using parametrized constructor, it is mandatory for the JAVA programmer to define parametrized constructor otherwise we will get compile time error.


Constructor Overloading in Java

Constructor overloading is one in which a class can have any number of constructors.Constructor name is similar but its signature must be different. Signature represents number of parameters, type of parameters and order of parameters. Here, at least one thing must be differentiated.

Example of Constructor Overloading


package com.example;

public class Cube {

	int length;
	int breadth;
	int height;

	public int getVolume() {
		return (length * breadth * height);
	}

	Cube() {
		length = 10;
		breadth = 10;
		height = 10;
	}

	Cube(int l, int b, int h) {
		length = l;
		breadth = b;
		height = h;
	}

	public static void main(String[] args) {
		Cube Obj1;
		Cube Obj2;
		Obj1 = new Cube();
		Obj2 = new Cube(5, 10, 30);
		System.out.println("Volume of Cube1 is : " + Obj1.getVolume());
		System.out.println("Volume of Cube1 is : " + Obj2.getVolume());
	}
}

Output :


Volume of Cube1 is : 1000
Volume of Cube1 is : 1500

As you can see in the above example that while creating the instance myobj, default constructor (Cube()) gets called however during the creating of Obj2, the arg-constructor (Cube(int l, int b, int h)) is called.Since both the constructors are having different initialization code the variables value are different in each case as shown in the output of the program.


Java – Constructor Chaining

Calling a constructor from the another constructor of same class is known as Constructor chaining.

Every constructor calls its superclass constructor.super() or this() must be the first statement in the constructor.If you are not writing super() as first line in the constructor, by default compiler will put super() as first statement in the constructor.So in constructor either super() or this() must be the first statement.This implies that this() and super() calls cannot both occur in the same constructor.

this and super keyword is used to call one constructor from other in Java. this() can be used to call other constructor of same class while super() can be used to call constructor from super class in Java.

this() will call no argument constructor of same class, while this(10) will call another constructor of same class which accepts one integer parameter. Similarly super() can be used to call no argument constructor of super class and super with parameter can be used to call other overloaded constructor of parent class.We will understand this with the help of below program.


Example of Constructor Chaining


public class ConstructorDemo {
	public ConstructorDemo() {
		System.out.println("Constructor with no argument");
	}

	public ConstructorDemo(String name) {
		this();
		System.out.println("Constructor with argument");
	}

	public static void main(String args[]) {
		ConstructorDemo demo = new ConstructorDemo("Constructor Chain Example");
	}
}

Output :


Constructor with no argument
Constructor with argument


public class ConstructorDemoSuper {

	public ConstructorDemoSuper() {
		System.out.println("Super Class Constructor with no argument");
	}

	public ConstructorDemoSuper(String name) {
		System.out.println("Super Class Constructor with argument");
	}
}

public class ConstructorDemo extends ConstructorDemoSuper {
	public ConstructorDemo() {
		super();
		System.out.println("Constructor with no argument");
	}

	public ConstructorDemo(String name) {
		super(name);
		System.out.println("Constructor with argument");
	}

	public static void main(String args[]) {
		ConstructorDemo demo1 = new ConstructorDemo("Constructor Demo");
		ConstructorDemo demo2 = new ConstructorDemo("Constructor Demo");
	}
}

Output :


Super Class Constructor with argument
Constructor with argument
Super Class Constructor with argument
Constructor with argument

Next Article
comments powered by Disqus