Sudeep Kumar Das

What is Constructor Overloading?

Interview Question Bank

Explanation

1165    0

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 :-

  1. public class Student {  
  2. //instance variables of the class  
  3. int id;  
  4. String name;  
  5.   
  6. Student(){  
  7. System.out.println("this a default constructor");  
  8. }  
  9.   
  10. Student(int i, String n){  
  11. id = i;  
  12. name = n;  
  13. }  
  14.   
  15. public static void main(String[] args) {  
  16. //object creation  
  17. Student s = new Student();  
  18. System.out.println(" Default Constructor values:  ");  
  19. System.out.println("Student Id : "+s.id + " Student Name : "+s.name);  
  20.   
  21. System.out.println(" Parameterized Constructor values:  ");  
  22. Student student = new Student(10, "David");  
  23. System.out.println("Student Id : "+student.id + " Student Name : "+student.name);  
  24. }  
  25. }  

Output :-

this a default constructor

 

Default Constructor values:

 

Student Id : 0

Student Name : null

 

Parameterized Constructor values: 

 

Student Id : 10

Student Name : David




Share:   

More Questions from Interview Question Bank Module 0