Constructor Overloading

Constructor Overloading

In sequence with the previous blog on constructors, we also need to understand one more concept which is very mandatory to learn i.e Constructor Overloading.

We have seen that constructors are used to passing values to the properties while instantiating the objects, and we also noted that it is mandatory to have a constructor in class and the data will be passed for every object we create of that class. But what if we want to break this rule, that is, we want in some cases only some values to be passed not all values? Normally this will throw an error, but here comes the constructor overloading.

Constructor Overloading means having more than one constructor in a class with either a different number of parameters or different parameters.

class Student{
    int roll_No;
    String name;
    int class;

    Student(int roll, String name; int class) {
    this.roll_No = roll;
    this.name = name;
    this.class = class;
    }
}
class Main{
    public static void main(String args[]){
        Student student1 = new Student(2, "Abhishek", 8);    
    }
}

For example, In the above code, we are creating an object named student1 of class Student and passing values to each property through the constructor.

Now, what if we don't want to send the class value of the student, only name and roll no need to initialize, but using the same code will throw an error, so we will implement constructor overloading in class Student.

class Student{
    int roll_No;
    String name;
    int class;

    Student(int roll, String name; int class) {
    this.roll_No = roll;
    this.name = name;
    this.class = class;
    }
    //Constructor overloaded: Here the number of parameters are                
    //less than the above constructor
    Student(int roll, String name) {
    this.roll_No = roll;
    this.name = name;
    }
}
class Main{
    public static void main(String args[]){
        Student student1 = new Student(2, "Abhishek");   
        Student student2 = new Student(1, "Madankar",51); 
    }
}

The above code will not give any error. "student1" object will invoke the second constructor because it has two arguments, and "student2" will invoke the first constructor because it has three arguments(int, String, int). So note, you can create the constructor with the no.of parameters needed, and also multiple constructors with different parameters. The passed arguments will decide which constructor to invoke.

Thank you for reading. Hope you understood the concepts.

#JustJavaThings

Did you find this article valuable?

Support Abhishek Madankar by becoming a sponsor. Any amount is appreciated!