logo codesdope

Constructor Overloading in Java


Suppose we have a 'Student' class and while making its object, we want to pass a name of it and if nothing is passed, then name should be "unknown". And yes! we can do this by having two constructors.

class Student{
  private String name;
  public Student(String n){
    name = n;
  }
  public Student(){
    name = "unknown";
  }
  public void printName(){
    System.out.println(name);
  }
}
class Cu1{
  public static void main(String[] args){
    Student a = new Student("xyz");
    Student b = new Student();
    a.printName();
    b.printName();
  }
}
Output
xyz
unknown

And it is working!
This is constructor overloading.

Now let's understand this example. Here, we made two objects of class 'Student'. While creating the object 'a', we passed a string "xyz" to Student() as Student a = new Student("xyz");. This invoke the constructor having a String parameter public Student(String n).

Similarly while creating the second object 'b' of the class Student, we didn't pass anything to Student() as Student b = new Student();, so the constructor having no parameter public Student() got invoked.

Condition for constructor overloading


The one condition for constructor overloading is that both constructors must have different parameters. Like in the above example, in the first constructor, we passed one String and in the second, nothing.
We can't make two constructors having exactly same arguments( e.g.- both having two ints ).
Either the number of argument or type of argument must vary.

We can have any number of constructors but with different arguments.

Knowing is not enough, we must apply. Willing is not enough, we must do.
-Bruce Lee

Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.