×

Constructor Overloading in Java

In Java, constructors can be overloaded just like methods. The idea of having multiple constructors with various parameter sets so that each function Object()  can carry out a particular task is known as function Object() overloading.

The below program will describe the constructor overloading.

Example

Teacher.java

import java.io.*;
import java.util.*;
//this program is for constructor overloading
public class Teacher {  
//declaring the instance variables of the class 
int tid;  
String tname;  
  
Teacher() //constructor without parameters
{  
System.out.println("default constructor/constructor with no parameters");  
}  
  
Teacher(int i, String n1) // constructor with having the parameters
{  
tid = i;  //assigning values
tname = n1;  
}  
 //main section 
public static void main(String[] args) {  
//creation of object for the Teacher class 
Teacher t = new Teacher();  
System.out.println("\nThe values of the Default constructor: \n");  
System.out.println("Teacher Id : "+t.tid + "\nTeacher's Name : "+t.tname);  //printing the values of the default constructor
  
System.out.println("\nConstructor with having the parameters: \n");  //printing the values of the parameterised constructor
Teacher t1= new Teacher(100, "Ramu");  //creating object for passing the parameters
System.out.println("Teacher Id : "+t1.tid + "\nTeacher Name : "+t1.tname);  
}  
}  

Output:

Constructor Overloading in Java

In the previous examples, there are two extra constructors-default and parameterised the Teacher class.

We must here comprehend the rationale for function Object() overloading. In certain cases, using several constructors is necessary to initialise different values of the class.

Moreover, we need to be aware that the Java compiler calls the default constructor when no constructors are used in the class. However, the default method is not called if we've used some methods in the class-default or parameterised. The function Object()  is invalid in this situation, according to an exception that the java compiler raises.

Consider the example below in which the object is not created using the default constructor.

Students.java

public class Students {  
String StudentsId;  
Students(String StudentsId){  
this.StudentsId = "Ravi " + StudentsId;   
}  
public static void main(String[] args) {  
// calling the default constructor
Students clg = new Students(); //it doesn't create students constructor.  
}  
} 

Output

Constructor Overloading in Java

By using this() method in the constructor overloading

This () method can also be used in the constructor. By using this keyword, one can access the elements of the parameterised constructor by passing the parameters in the this() method.

The below example will describe the use of this keyword.

Teacher.java

import java.io.*;
import java.util.*;
public class Teacher //creating the Teacher class
{  
//declaring the instance variables of the class
int tid,tsalary;  
String tname,contactNo,teachingCollegeName;  
  
Teacher(String contactNo, String teachingCollegeName, int tsalary){  
this.contactNo = contactNo;  
this.teachingCollegeName = teachingCollegeName;  
this.tsalary = tsalary;  
}  
  
Teacher(int tid, String tname) //parameterised constructor
{  
this("9834563214", "IIT Hyderabad", 45000);  
this.tid = tid;  
this.tname = tname;  
}  
//main section 
public static void main(String[] args) {  
//creation of object for the Teacher class 
Teacher t = new Teacher(101, "Sita");  
System.out.println("Printing the details of the Teacher: \n");  
System.out.println("Name: "+t.tname+"\nId: "+t.tid+"\nContact No: "+t.contactNo+"\nTeaching College Name: "+t.teachingCollegeName+"\nSalary: "+t.tsalary);  
}  
}  

Output

Constructor Overloading in Java

There are some of the important steps that are to be followed in constructor overloading:

  • When we want to call the constructor, it should be in the first line of the constructor.
  • When no parameterised constructor is created, the compiler will first go to the default constructor.
  • The constructor cannot be called in the recursive process.

Related Topics

Implementing Queue Using Array in Java

We can implement queue by using array in Java. The queue is a linear data structure, and the array is one of the simplest data structures. Before implementing a queue...

4 minutes read.

Console Errors in Java

An unlawful motion taken through the person that reasons this system to act abnormally is amistake until this system is compiled or run; maximum programming mistakes pass unnoticed.The software is...

3 minutes read.

ArrayList vs Vector in Java

ArrayList Vs. Vector in Java In Java, the two classes ArrayList and Vector both are associated with Java Collections Framework. Both classes implement java.util.List interface. Even so, these classes have noticeable...

4 minutes read.

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

11 minutes read.

GCD Program in Java

GCD Program in Java The GCD program in Java outputs the GCD of the given numbers. In mathematics, Greatest Common Divisor (GCD), Greatest Common Factor or Highest Common Factor (HCF) of...

14 minutes read.

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

Java Externalization

What is Externalization in Java? Externalization is a concept that is advanced to serialization. Serialization is a concept where we can transfer an object from our JVM ( Java virtual machine...

3 minutes read.

Array Programs in Java

Array Programs in Java: An array is a data structure that stores similar elements in a contiguous memory location. In Java, an array is an object that stores the same...

7 minutes read.

Java File Extension

A computer file's suffix is called its file extension. It is easily recognized since it appears immediately after a period (.) in the file name. Consider the file Demo.java as an...

3 minutes read.

Java String replaceFirst() method

This method replace the first substring with user specified String. Syntax: public String replaceFirst(String Regexp, String Replacement) Parameter: Regexp : Regular Expression Replacement : the String which would replace found expression Return: a string Java String replaceFirst()...

1 minute read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.

Set Matrix Zeros in Java

In coding round interviews, it is frequently asked as the most significant challenge. an m*n matrix is provided. Set the entire column and row of the matrix to 0 if any...

6 minutes read.

How to Return Value from Lambda Expression Java?

What is Lambda Expression in Java? In Java 8, Lambda Expressions were introduced.A lambda expression is a brief section of code that accepts input and outputs a value. Similar to methods,...

4 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

Difference between String and Char Array in Java

We are heading to examine some significant differences between String and Character arrays. Both char arrays and String hold the series of characters and are utilised as a cluster of...

3 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.

Empty Statement in Java

The three sorts of statements in Java are control, expression, and declaration statements. Additionally, another statement is referred to as an empty statement. In this section, we will discuss about...

4 minutes read.

Java RMI

What is RMI in Java? A framework for developing distributed Java applications is provided by the RMI (Remote Method Invocation) API. An object can call methods on an object running in...

4 minutes read.

public static void main string args meaning in java

In java main() method is the initial point for execution of the program. If a program doesn’t contain the main method, the program will not execute. JVM(java virtual machine) starts...

3 minutes read.