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.
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
- class Student5{
- int id;
- String name;
- int age;
- Student5(int i,String n){
- id = i;
- name = n;
- }
- Student5(int i,String n,int a){
- id = i;
- name = n;
- age=a;
- }
- void display(){System.out.println(id+" "+name+" "+age);}
- public static void main(String args[]){
- Student5 s1 = new Student5(111,"Karan");
- Student5 s2 = new Student5(222,"Aryan",25);
- s1.display();
- s2.display();
- }
- }
Output
111 Karan 0 222 Aryan 25
No comments:
Post a Comment