Constructor in Java5 min read

Introduction

Constructor in Java is used to initialize a newly formed object before it can be utilized. When we create an instance of a class, it is necessary to initialize all the variables in the class. This initialization is performed automatically by a special function, called a constructor. The constructor initializes an object immediately upon its creation. The name of the constructor must be the same as the name of the class in which it resides. A constructor has no return type, not even void. Constructors may or may not have an argument.

Points to remember while creating a constructor in Java

  • When an object is created, a constructor is called automatically and immediately, before the new operator completes.
  • We can include one or more constructors in the class definition, provided that their signatures must be different.
  • Every class has a constructor. If we do not provide any constructor, the system provides a default constructor.
  • The default constructor allocates memory and initializes instance variables and does & Constructors are not instance methods since they don’t belong to an object. Actually, according to the specifications of the Java language constructors can’t be declared anything beyond this as static have Constructors are responsible for creating objects, and hence they exist before any objects are created.
  • They are like static member subroutines, but they are not and cannot be declared as static.

The steps that the compiler follows while executing the constructor are:

  • At First, the compiler gets a block of unused memory in the heap. This help is large enough to hold objects of the specified type.
  • The instance variables of the object initialize. The declaration of instance variable specifies an initial value, it is computed and stored in an instant variable otherwise default initial value is used.
  • The actual parameters in the constructor (if any are evaluated and the values are evaluated and the values are assigned to the formal parameters of the constructor.
  • The constructor body is executed.
  • An object reference is returned as the value of the constructor call.

Types of Java constructors

Different types of constructor in java
Different types of constructors in java

Different types of constructors in Java:

  1. Default constructor
  2. No argument constructor
  3. Parameterized constructor
  4. Copy constructor

Default constructor

When the constructor doesn’t have a parameter, it is called the “Default constructor.” We don’t have to mention the default constructor in the program. It is called automatically when an object of the class is created.

public class Teacher{  
	int sal;  
	String name;  
  
	//method to display the value of sal and name  
	void display(){
		System.out.println(sal+" "+name);
    }  
  
	public static void main(String args[]){  
		//creating objects  
		Teacher s1 = new Teacher();  // Here, the default contructor will be called so that the class object can be initialized
		Teacher s2 = new Teacher();  // Here also, the default constructor will be called
      
		//displaying values of the object  
		s1.display();  
		s2.display();  
	}  
}  

Output:

0 null
0 null

No argument constructor

A constructor that has no parameter is known as the default constructor. If we don’t define a constructor in a class, then the compiler creates a default constructor(with no arguments) for the class. And if we write a constructor with arguments or no arguments then the compiler does not create a default constructor.

public class Main {
  	int a;
  	// constructor with no parameter
	private Main() {
    	a = 5;
    	System.out.println("Constructor is called");
	}

	public static void main(String[] args) {
		// calling the constructor without any parameter
    	Main obj = new Main();
		System.out.println("Value of a: " + obj.a);
	}
}

Parameterized constructor

The parameter builder is known as the parameter builder. If the class fields with your own values are to be initialized, then use a parameterized constructor. Most often, a builder accepting one or more parameters will be needed. Parameters are added to a builder just as they are added to a method and declared in brackets following the name of the builder.

public class Teacher{  
    int sal;  
    String name;  
    // parameterized constructor  
    Teacher(int a,String e){  
    	sal = a;  
    	name = e;  
    }  
    //method
    void display(){
    	System.out.println(sal+" "+name);
    }  
   
    public static void main(String args[]){  
    	//creating objects and passing values  
    	Teacher s1 = new Teacher(15000,"jyoti");  
    	Teacher s2 = new Teacher(12000,"Anuradha");  
    	//calling method to display the values of object  
    	s1.display();  
    	s2.display();  
	}  
}  

Output:

15000 jyoti
12000 Anuradha

Copy Constructor

A Java class copy constructor is a constructor that creates an object with a different object in the Java class. This is helpful to copy a complex object with various fields or to make a thorough copy of an object that already exists.

Example:

//Java program to initialize the values from one object to another object.  
public class Teacher{  
    int sal;  
    String name;  
    //constructor to initialize integer and string  
    Teacher(int s, String n){  
    	sal = s;  
    	name = n;  
    }  
    //constructor to initialize another object  
    Teacher(Teacher s){  
    	sal = s.sal;  
    	name =s.name;  
    }  
    void display(){
    	System.out.println(sal+" "+name);
    }  
   
    public static void main(String args[]){  
    	Teacher s1 = new Teacher(15000,"jyoti");  
    	Teacher s2 = new Teacher(s1);  
    	s1.display();  
    	s2.display();  
   }  
} 

Output :

15000 jyoti
15000 jyoti

Constructor Overloading

  • Java allows defining two or more methods with the same name within the same class, as long as, their parameter declaration is different,
  • Constructors can be overloaded and constructor overloading means multiple Constructors functions with different signatures.
  • Constructors overloading is allowed if the number of parameters or types of parameters is different.
  • When an object is declared, Java executes the version of the Constructors whose parameters match the arguments.
  • Constructors overloading allows appropriate initialization of objects on creation, depending, on the Constructor invoked.

Example:

public class Sample{
	int roll; 
	Boolean feesPaid;
	String result;
  
	// default Constructor
	Sample(){
		roll =10;
		feesPaid = true; 
		result =new String("FAIL");
    }
  
	//parameterized Constructor
	Sample (int rn, Boolean fp, String rs){
		roll = rn;
		feesPaid = fp; 
		result = rs;
	}

  	void display(){
    	System.out.println(roll + " " + feesPaid + " " + result);
    }
  	
  	public static void main(String args[]){  
    	Sample sample1 = new Sample();  
    	Sample sample2 = new Sample(11, true, "PASS");  
    	sample1.display();  
    	sample2.display();  
   }
}

Output:

10 true FAIL
11 true PASS

Share:

Leave a Reply