Methods overloading is where a class has methods having the same name but different parameters. Importance of method overloading The m...
Methods overloading is where a class has methods having the same name but different parameters.
Output
Importance of method overloading
The main reason to use method overloading is to increase program readability.Think of a scenario where you have addition method taking different parameters.eg add(int a ,int b) and addMethod(int a, int b,int c).Reading such code can be difficult.With method overloading we can use the same method name to include the two methods in the class i.e add(int a,int b) and add(int a,int b,int c)
Two ways of overloading.
There are two ways of overloading methods.
1.Changing Number of arguments
2.Changing Data types
public class AddMethods { public void addNumbers(int a,int b) { int sum=a+b; System.out.println("Sum is " +sum); } public void addNumbers(int a,int b,int c) { int sum=a+b+c; System.out.println("Sum is " +sum); } AddMethods() { addNumbers(10,14); addNumbers(10,14,56); } public static void main(String args[]) { new AddMethods(); } }Output
2.Changing Data types
public class AddMethods { public void addNumbers(int a,int b) { int sum=a+b; System.out.println("Sum is " +sum); } public void addNumbers(double a, double b) { double sum=a+b; System.out.println("Sum is " +sum); } AddMethods() { addNumbers(10,14); addNumbers(10.57,14.67); } public static void main(String args[]) { new AddMethods(); } }