×

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

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.

Java Program to generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The...

3 minutes read.

Undo and Redo Operations in Java

Undo and redo operation are the most widely used operation while dealing with file. In this section, we will discuss how to implement undo and redo operation in Java. Undo Redo...

2 minutes read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

Java Rename File

Renaming a file is the process of changing its name. Using the renameTo() function of the Java File class, renaming operations are possible. A file can be renamed using Java's renameTo()...

3 minutes read.

Timestamp Operation in Java

JDBC escape syntax is supported by Timestamp's formatting and parsing functions. Additionally, it adds support for fractional seconds values for SQL TIMESTAMP.java.util.Date is wrapped in a lightweight wrapper that enables...

3 minutes read.

Java Imageio

The javax.imageio package contains the final class known as Java ImageIO. For easy image reading, writing, and simple encoding and decoding, the class offers a convenient way. The class offers...

4 minutes read.

Java ArraylistRemove() Time Complexity

In this tutorial, we will learn about how we can remove time complexity in Java ArrayList. But unless we will not learn what is ArrayList, we don’t understand this process....

7 minutes read.

Addition Program in Java

Addition Program in Java We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand...

3 minutes read.

Java Tokens

Classes and methods are included in the Java program. The procedures also provide the expressions and statements required to finish a specific operation. Tokens make up the sentences and expressions...

4 minutes read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Minimum Difference Between Groups of Size Two in Java

There is given an array with various integers in it. The goal is to divide the elements into distinct groups, each of which has just two, so that the difference...

3 minutes read.

Convert IP to Binary in Java

Fundamental conversion, such as going from binary to decimal or vice versa, is a crucial activity in computers. Understanding IP addressing and subnetting is crucial for networking. The primary networking...

4 minutes read.

MOOD Factors to Assess a Java Program

In this tutorial, we will comprehendthe meaning of mood factors in Java. For the development of any software system,the quality of anapplication is important. It is more important to maintain large-scale...

4 minutes read.

How to Create Different Packages for Different Classes in Java

Packages in Java In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points...

7 minutes read.

Binary Search Java

Binary search is a search mechanism for key elements from the given List/Array. In Binary search, the search mechanism is followed by dividing the array into parts; hence the search...

3 minutes read.

Program to find the duplicate characters in a string

Problem statement You have given with a string and your task is to find out the repeated characters from the string and print them. If no character is repeated, then you...

2 minutes read.

Java copy file

There are for the most part 3 methods for duplicating documents utilizing java language. They are as given underneath: Utilizing File StreamUtilizing FileChannel ClassUtilizing Files class. 1. Using File Stream: Here we are...

5 minutes read.

Swastika Pattern in Java

This part teaches us how to create the Swastika Pattern in Java utilizing user-defined columns and rows as well as stars or other special characters.A Java pattern application that is...

2 minutes read.