Method Overloading in Java

Method Overloading in Java
Method Overloading in Java 1

Method overloading is one of the features of OOP if there is a class with the same name with a different number of parameters or different data types

Method overloading has 2 types

Number of parameters

For overloading a method, two methods can have same name but , number of parameters differ

method(int, int)

method(int, int, int)

Example

class Addmethod{  
    static int add(int a,int b){
        return a+b;
    }  
    static int add(int a,int b,int c){
        return a+b+c;
    }  
}  
    class Addition{  
    public static void main(String[] args){  
    System.out.println(Addmethod.add(10,20));  
    System.out.println(Addmethod.add(45,73,41));  
    }
}  
30
159

In the above example add( ) method is overloaded with respective of number of parameters.so if there is two arguments the first method will be executed add(int a,int b) , if there is there is three arguments the second method will be executed add(int a,int b,int c)

Data type of parameters.

For overloading a method, two methods can have same name but , number of parameters should be same and Data type of parameters differ

method(int, int)

method(int, float)

Example

class Addmethod{  
    static int add(int a,int b){
        return a+b;
    }  
    static double add(double a,double b){
        return a+b;
    }   
}  
    class Addition{  
    public static void main(String[] args){  
    System.out.println(Addmethod.add(10,20));  
    System.out.println(Addmethod.add(45.4,73.4));  
    }
}  
30
118.80000000000001

In the above example add( ) method is overloaded with respective of Data type of parameters. so if there is two arguments which have int as the datatype. the first method will be executed add(int a,int b)

so if there is two arguments which has double as the datatype . the second method will be executed add(double a,double b)

Why Method Overloading is not possible by changing the return type of method?

It is not possible to decide to execute which method based on the return type. This is called ambiguity.

Default image
Vishal Devxo
Vishal is a DevOps engineer and a Backend developer, he spends all his time for creating good tutorials with better visuals and blogging, developed some projects based on Python-Django, some hacking modules and scripts in python
Leave a Reply