Constructor overloading in Java is a technique of having more than one constructor with different parameter lists.
They are arranged in a way that each constructor
performs a different task. They are differentiated by the compiler by the
number of parameters in the list and their types.
Example:
class Student{
int id;
String name;
int age;
//creating a two argument constructor
Student(int i,String n){
id = i;
name = n;
}
//creating a three argument constructor
Student(int i,String n,int a){
id = i;
name = n;
age=a;
}
//method to display the values
void display(){
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[]){
//creating objects and passing values
Student s1 = new Student(111,"Kalyan");
Student s2 = new Student(222,"Ashraf",25);
//calling method to display the values of object
s1.display();
s2.display();
}
}
In above example, there are two constructors with
different number of parameters. Corresponding constructor is called depending
on parameters using to initialize the object.
No comments:
Post a Comment