Since I have found so many examples and conclusions about Method Overloading but still I am confusing in real time how we are using it.
First of all method overloading is a class level activity means within that class we are overloading a method with same name but different arguments like
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}
and after we are calling this method like
public static void main(String args[]){
ClassName obj=new ClassName ();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
Suppose instead of this I will take two separate method like
void method1(int a,int b){System.out.println(a+b);}
void method2(double a,double b){System.out.println(a+b);}
And I will call this 2 methods same as above
public static void main(String args[]){
ClassName obj=new ClassName ();
obj.method1(20,20);
obj.method2(10.5,10.5);
}
In both the case for both the methods the activities are same then what is the exact need of overloading/polymorphism in this case.
Somewhere I found that Method overloading increases the readability of the program can anybody please specify that only because of this line we are using method overloading.
Thanks.
Suppose we didn't have method overloading in Java.
Instead of :
System.out.println("String");
System.out.println(5);
System.out.println('c');
...
we would have :
System.out.printlnString("String");
System.out.printlnInt(5);
System.out.printlnChar('c');
...
or even worse :
System.out.println1("String");
System.out.println2(5);
System.out.println3('c');
...
Both alternatives would make the code less readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With