Constructor Overloading is a technique in Java in which a class can have any number of constructors but each has different parameter lists.The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.
Example of Constructor Overloading:
class Student{
int id;
String name;
int age;
Student(int i,String n){
id = i;
name = n;
}
Student(int i,String n,int a){
id = i;
name = n;
age=a;
}
void show() { System.out.println (id+" "+name+" "+age); }
public static void main(String []args){
Student s1 = new Student(123,"vishwa");
Student s2 = new Student(456,"dolly",26);
s1.show();
s2.show();
}
}
Output:123 vishwa 0
456 dolly 26
Note: constructor overloading is same as method overloading in Java
No comments:
Post a Comment