Method Overloading and Constructor overloading in java

Method Overloading and Constructor overloading in java

Method Overloading 

It is possible to define two or more methods within the same class that share the same name, as long as their parameter declaration are different.In this case, methods are said to be overloaded and the process is  referred  to as method overloading.Method overloading is one the ways that Java supports polymorphism.

Example:

public class Pairosoft{
    void method(){
    System.out.println("1st method");
    }

    void method(int a){
    System.out.println("2nd method");
    System.out.println("value of A is:"+a);  
    }

    void method(int a,int b){
        System.out.println("3rd method");
        System.out.println("value of a is:"+a);
        System.out.println("value of b is:"+b);
    }

    public static void main(String[] args) {

        Pairosoft p1=new Pairosoft();
        p1.method();
        p1.method(10);
        p1.method(20,30);
    }
 }


Output:-

1st method
2nd method
value of A is:10
3rd method
value of a is:20
value of b is:30



Constructor overloading
In Constructor overloading class can have any number of constructors that differ in parameter list.we will seen one example of constructor overloading.

Example:

public class Pairosoft{ 
     Pairosoft(){                       //constructor declaration without parameter
    System.out.println("1st Constructor");
    }
     Pairosoft(int a){               //constructor declaration with parameter
    System.out.println("2nd Constructor");
    System.out.println("value of A is:"+a);   
    }
    Pairosoft(String a,int b){   //constructor declaration with parameter
        System.out.println("3rd Constructor");
        System.out.println(a);
        System.out.println("value of b is:"+b);
    }
    public static void main(String[] args) {
        Pairosoft p1=new Pairosoft();                         /call the constructor 
        Pairosoft p2=new Pairosoft(10);                    //call the constructor 
        Pairosoft p3=new Pairosoft("hello...",10);     //call the constructor 
    }
}

 Output:-

1st Constructor
2nd Constructor
value of A is:10
3rd Constructor
hello...
value of b is:10










More will come idea if you watch this video:-






Post a Comment

0 Comments