google.com, pub-8786015629279405, DIRECT, f08c47fec0942fa0 Constructor Overloading in Java

Constructor Overloading in Java

0


Constructor Overloading

 In Java, Constructor overloading is a technique in which a class have a number of constructor that must be different in the argument list.
The compiler identify these constructor by taking into account the number of parameters in the list and their type.

They are arranged in a way that each constructor performs a different task.

Syntax with Example:

 public class classname {
 declare instance variables;
 classname();
 {
 default constructor;
 }
 classname(argument list 1)
 {
 parameterized constructor;
}

classname(argument list 2)
 {
 parameterized constructor;
}
 public class Main {
 public static void main(String args[]) {
  classname objectname=new classname();
  classname objectname=new classname(argument list 1); 
  classname objectname=new classname(argument list 2);
}
}

Example Constructor Overloading

//Java program to overload constructors  
class Student{  
    int id;  
    String name;  
    int age; 

    //creating one arg constructor
    Student(int i){
    id=i;
    } 
//creating two arg constructor  
    Student(int i,String n){  
    id = i;  
    name = n;
     }  
    //creating three arg constructor  
    Student(int i,String n,int a){  
    id = i;  
    name = n;  
    age=a;  
    }  
    void display(){System.out.println(id+" "+name+" "+age);}

    class const{
    public static void main(String args[]){  
    Student s1 = new Student(111);
    Student s2 = new Student(222,"Karan");  
    Student s3 = new Student(333,"Aryan",25);  
    s1.display();  
    s2.display();
    s3.display();  
   }  


Output:
 111,null,0
  222, Karan,0
  333, Aryan,25

Watch Full Video on Youtube..

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Thank you for your interest 😊

We will back shortly after reviewing...

Thank you for your interest 😊

We will back shortly after reviewing...

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top