Java Tutorial: Constructor Overloading with Example

We know earlier what is a constructor, default constructor, types of constructors and their advantages and place in Java language. Let us know one more concept of constructors known as constructor overloading.

Like method overloading, Java also supports constructor overloading. Writing multiple constructors, with different parameters, in the same class is known as constructor overloading. Depending upon the parameter list, the appropriate constructor is called when an object is created.

Let us see the Constructor Overloading concept programmatically.
public class Student
{
  public Student()                          // I ,  default constructor
  {
    System.out.println("Hello 1");
  }
  public Student(String name)               // II,  parameterized constructor with single parameter
  {
    System.out.println("Student name is " + name);
  }

  public Student(String name, int marks)    // III,  parameterized constructor with two parameters
  {
    System.out.println("Student name is " + name + " and marks are " + marks);
  }

  public static void main(String args[])
  {
    Student std1 = new Student();                 // calls I
    Student std2 = new Student("Mr.Reddy");       // calls II
    Student std3 = new Student("Mr.Raju", 56);    // calls III
  }
}

Constructor Overloading

The Student() constructor overloading is done three times – one default constructor, the second one with string parameter and the third one with string and int parameters. In the main() method, three objects std1, std2 and std3 are created by using overloaded constructors. Depending upon the number of parameters and their data type order, the appropriate constructor is called.

The advantage or uses of constructor is it gives properties to the object at the time of object creation itself. For std2 object, name is given and std3 object name with marks are given.

Have more understanding on Constructors

View All for Java Differences on 90 Topics

Leave a Comment

Your email address will not be published.