Method overloading with type promotion:
One type is promoted to another implicitly if no matching datatype is found. Let’s understand the concept by the figure given below:
Example: Method Overloading with Type Promotion
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Multiplication{ void prod(long l,long b) { System.out.println("Product is "+(l*b)) ; } void prod(int l, int b,int h) { System.out.println("Product is "+(l*b*h)); } public static void main (String[] args) { Multiplication mul = new Multiplication(); mul.prod(2,3); /*automatic type conversion from prod(int,int) to prod(long,long) */ mul.prod(2,3,4); //prod(int l, int b,int h) is called. } } |
1 2 3 |
Output: Product is 6 Product is 24 |
If there are matching type arguments in the method, type promotion is not performed:
Example: Method Overloading with Type Promotion if matching found
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class OverloadingExample{ void sum(int a,int b){System.out.println("Integer argument method is invoked");} void sum(long a,long b){System.out.println("Long argument method is invoked");} public static void main(String args[]){ OverloadingExample obj=new OverloadingExample(); obj.sum(1234,12345);//now integer argument sum() method gets invoked} } |
1 2 |
Output: Integer argument method is invoked |
Example: Method Overloading with Type Promotion if matching found
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class OverloadingEx{ void sum(int a, int b){System.out.println("Integer argument method is invoked");} void sum(int a, long b){System.out.println("Long argument method is invoked");} public static void main(String args[]){ OverloadingEx obj=new OverloadingEx(); obj.sum(20,20);//now integer argument sum() method gets invoked} } |
1 2 |
Output: Integer argument method is invoked |
If there are no matching type arguments in the method, and each method promotes similar number of arguments, there will be ambiguity:
Example:
1 2 3 4 5 6 7 8 9 |
class OverloadingEx3{ void sum(int a,long b){System.out.println("a method invoked");} void sum(long a,int b){System.out.println("b method invoked");} public static void main(String args[]){ OverloadingEx3 obj=new OverloadingEx3(); obj.sum(15,20);// this is an ambiguity & result in error } } |
1 2 3 |
Output: Compile Time Error One type is not de-promoted implicitly for example double cannot be de-promoted to any type implicitly. |
Why Method Overloading is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because there may occur ambiguity. Let’s see how ambiguity may occur in the below example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Cal { int sum(int a,int b) { System.out.println(a+b); } double sum(int a,int b) { System.out.println(a+b); } public static void main(String args[]) { Cal obj=new Cal(); int result=obj.sum(20,20); //Compile Time Error } } |
1 2 3 |
Output: Error Because here Java did not understand which method to call. |