What is Constructor Overloading?
Constructor overloading is a concept of having more than one constructor with different parameters list, in such a way so that each constructor performs a different task. For e.g. Vector class has 4 types of constructors. If you do not want to specify the initial capacity and capacity increment then you can simply use default constructor of Vector class like this Vector v = new Vector(); however if you need to specify the capacity and increment then you call the parameterized constructor of Vector class with two int arguments like this: Vector v= new Vector(10, 5);
Constructor overloading Program :-
- public class Student {
- //instance variables of the class
- int id;
- String name;
- Student(){
- System.out.println("this a default constructor");
- }
- Student(int i, String n){
- id = i;
- name = n;
- }
- public static void main(String[] args) {
- //object creation
- Student s = new Student();
- System.out.println(" Default Constructor values: ");
- System.out.println("Student Id : "+s.id + " Student Name : "+s.name);
- System.out.println(" Parameterized Constructor values: ");
- Student student = new Student(10, "David");
- System.out.println("Student Id : "+student.id + " Student Name : "+student.name);
- }
- }
Output :-
this a default constructor
Default Constructor values:
Student Id : 0
Student Name : null
Parameterized Constructor values:
Student Id : 10
Student Name : David