CONSTRUCTOR OVERLOADING

Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.The compiler differentiates these constructors by taking the number of parameters, and their type.
In other words whenever same constructor is existing multiple times in the same class with different number of parameters or order of parameters or type of parameters is known asConstructor overloading
In general constructor overloading can be used to initialized same or different objects with different values.

Syntax

class  ClassName
{
ClassName()
{
..........
..........
}
ClassName(datatype1 value1)
{.......}
ClassName(datatype1 value1, datatype2 value2)
{.......}
ClassName(datatype2 variable2)
{.......}
ClassName(datatype2 value2, datatype1 value1)
{.......}
........
}

Example

  1. class Student5{  
  2.     int id;  
  3.     String name;  
  4.     int age;  
  5.     Student5(int i,String n){  
  6.     id = i;  
  7.     name = n;  
  8.     }  
  9.     Student5(int i,String n,int a){  
  10.     id = i;  
  11.     name = n;  
  12.     age=a;  
  13.     }  
  14.     void display(){System.out.println(id+" "+name+" "+age);}  
  15.    
  16.     public static void main(String args[]){  
  17.     Student5 s1 = new Student5(111,"Karan");  
  18.     Student5 s2 = new Student5(222,"Aryan",25);  
  19.     s1.display();  
  20.     s2.display();  
  21.    }  
  22. }

Output

111 Karan 0
222 Aryan 25

No comments:

Post a Comment