Programs

What is Constructor Overloading in Java

Demand for web applications is on the rise globally. Java has emerged as a preferred choice for developers with the need for large-scale programming. Java‘s popularity relies on its dynamic features, user-friendly interface, and high compatibility with leading operating systems. The language has a rich API. Another advantage of Java is that it offers robust community support and excellent documentation services. Do not forget the suite of development tools offered by Java. 

What do you mean by constructors in Java?

Constructors in Java are mainly used for initializing the state of the object. Similar to methods, constructors consist of a group of instructions or statements which have to be executed when an object is being created. 

What is the need for a Constructor in Java?

To explain the need for a constrictor in Java, let us take an example of a box. Consider the box to be a class. The box will have different variables like length, width, and height. When it is time to create an object, the box class will not have any defined values for its dimensions. When new objects are created, the constructors assign values to the class variables in two ways – by various parameters passed by the programmer or by using default Java constructors. 

What do you mean by Constructor Overloading in Java?

In constructor overloading, multiple constructors of the same class are defined. However, every constructor should have a unique signature or specific input parameters. The constructor overloading program in Java enables a single class to have more than one constructor, which differs by the list of arguments passed. Every overloaded constructor is used to perform various class tasks. 

The Java compiler identifies the overloaded constructors based on parameter types, parameter lists, and the amounts of input parameters. It is quite obvious that the overloaded constructors have different signatures. The signature of the constructor will contain its parameter types and its name. Sometimes ambiguity issues arise when two class constructors have an identical signature. In such a situation, the compiler cannot differentiate between the two. Therefore it displays an error notification. Sometimes, there are overloaded constructors with different signatures. In this case, the compiler ascertains that the conductor is invoked depending on the number of input parameters of the different objects. 

Example of Constructor Overloading

In this example, we are looking to create two objects of class StudentData. One object uses a default constructor, while the other uses a parameterized constructor. Both the constructors have separate initialization codes. It is possible to create constructors of any numbers with different-2 initialization codes for different-2 purposes. 

StudentData.java

class StudentData

{

   private int stuID;

   private String stuName;

   private int stuAge;

   StudentData()

   {

       //Default constructor

       stuID = 100;

       stuName = “New Student”;

       stuAge = 18;

   }

   StudentData(int num1, String str, int num2)

{

       //Parameterized constructor

       stuID = num1;

       stuName = str;

       stuAge = num2;

   }

   //Getter and setter methods

   public int getStuID() {

       return stuID;

   }

   public void setStuID(int stuID) {

       this.stuID = stuID;

   }

   public String getStuName() {

       return stuName;

   }

   public void setStuName(String stuName) {

       this.stuName = stuName;

}

   public int getStuAge() {

       return stuAge;

   }

   public void setStuAge(int stuAge) {

       this.stuAge = stuAge;

   }

   public static void main(String args[])

   {

       //This object creation would call the default constructor

       StudentData myobj = new StudentData();

       System.out.println(“Student Name is: “+myobj.getStuName());

       System.out.println(“Student Age is: “+myobj.getStuAge());

       System.out.println(“Student ID is: “+myobj.getStuID());

 

       /*This object creation would call the parameterized

        * constructor StudentData(int, String, int)*/

       StudentData myobj2 = new StudentData(555, “Chaitanya”, 25);

       System.out.println(“Student Name is: “+myobj2.getStuName());

       System.out.println(“Student Age is: “+myobj2.getStuAge());

       System.out.println(“Student ID is: “+myobj2.getStuID()); 

  }

}

 

Output:

 

Student Name is: New Student

Student Age is: 18

Student ID is: 100

Student Name is: Chaitanya

Student Age is: 25

Student ID is: 555

Reference: https://beginnersbook.com/2013/05/constructor-overloading/ 

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Understanding the function of this () in constructor overloading

public class OverloadingExample2

{

   private int rollNum;

   OverloadingExample2()

   {

      rollNum =100;

   }

   OverloadingExample2(int rnum)

   {

      this();

      /*this() is used for calling the default  

       * constructor from parameterized constructor.

       * It should always be the first statement 

       * inside constructor body.

       */

      rollNum = rollNum+ rnum;

   }

public int getRollNum() {

  return rollNum;

   }

   public void setRollNum(int rollNum) {

  this.rollNum = rollNum;

   }

   public static void main(String args[])

   {

  OverloadingExample2 obj = new OverloadingExample2(12);

       System.out.println(obj.getRollNum());

    }

}

 

Output

 

112

Reference: https://beginnersbook.com/2013/05/constructor-overloading/
upGrad’s Exclusive Software Development Webinar for you –
upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

 

In the program mentioned above, the parameterized constructor is called during the creation of the object. The default constructor is invoked as this () is placed in the parameterized constructor. The variable rollNum is initialized. 

Another Example:

When you do not implement any constructor, the java compiler will insert a default constructor into the code during compilation. However, the compiler does not do this when you implement any constructor. See the example here to understand this point better:

public class Demo

{

   private int rollNum;

   //We are not defining a no-arg constructor here

 

   Demo(int rnum)

   {

      rollNum = rollNum+ rnum;

   }

   //Getter and Setter methods

 

   public static void main(String args[])

   {

      //This statement would invoke no-arg constructor

      Demo obj = new Demo();

   }

}

 

Output:

Exception in thread “main” java.lang.Error: Unresolved compilation 

Problem: The constructor Demo() is undefined

Popular Courses & Articles on Software Engineering

Explaining the use of constructor overloading

With construction overloading, it becomes possible to enable an object’s creation of a specific class in different ways. Therefore this concept is used in various Java programs depending on the programmer’s requirement. When using constructor overloading in Java, it is possible to initialize the objects with different data types. 

For example, consider there is an object with three class instance variables. You must assign a particular value to the second instance variable and default values to the other variables. Accomplish this by declaring multiple constructors as per different signatures in the constituent class. 

Advantages of Constructor Overloading in Java

Mentioned below are the key advantages of using constructor overloading while you are writing Java programs:

  • You can initialize the class instances in various ways by using constructor overloading.
  • With constructor overloading, you can accomplish static polymorphism. 
  • Each overloaded constructor performs different tasks for specified purposes.
  • Constructor overloading in Java smoothens the process of defining multiple constructors in a single class with uniquely specific signatures. 

Conclusion

This article discusses the constructor overloading program in Java and its benefits. There is more than one constructor of a class with different signatures when there are overloaded constructors. For compiling, every constructor must have different parameter lists. A parameter list will comprise the types and orders of arguments. It is impossible to have two constructors with the same parameter lists in a class. 

upGrad’s Full Stack Development Certificate Program for software developers and tech professionals

Whether you are new to the software development industry or looking to upskill, you must learn new skills and technologies through relevant courses. Full-stack development is one such course. 

upGrad offers Executive Program in Software Development to interested candidates, exclusively designed for IT professionals, software developers, tech support professionals, analysts, and recent graduates looking to venture into the software development arena. 

You will be highly skilled in JavaScript and learn Microservices and MERN Stack with this course. Along with learning almost 10+ programming languages and tools, you will also learn the various tools used extensively on Facebook, Walmart, Netflix, and LinkedIn. The program provides an immersive learning experience on Cloud Labs. 

Students taking up this certificate program will have the opportunity to design, develop, test, and deploy web applications in the Capstone project. Learners get one-to-one career mentorship sessions with leading industry mentors with these benefits. Upon completing the course, you can work as a full-stack developer, a UI developer, a front-end, and a back-end developer. 

Apply now to enroll in the course!

What is the use of a constructor in Java?

A constructor in Java is used to initialize objects and create an object of a class. You can also set initial values for object features and attributes. A constructor is like a block of codes, similar to a method or a process.

Does constructor overloading take place for static class?

Interestingly, static conductors cannot be overloaded or inherited. A static conductor is invoked automatically. The user has no control when the static constructor is executed in the program.

Is there a difference between constructor overloading and method overloading?

A method is used to perform certain class functions, whereas a constructor initializes an object. When you create an object, constructors get invoked implicitly. However, methods have to be called by the user explicitly.

Want to share this article?

Prepare for a Career of the Future

Leave a comment

Your email address will not be published. Required fields are marked *

Our Best Software Development Course

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks