- Method Overloading
- Method overloading by changing the number of arguments-
- Example-
- Method overloading using different data types of the arguments-
- Example-
- Output-
- Note :
- Example-
- Overloading main() method
- Output-
- Implementing type promotion with Method overloading
- Example-
- Output-
- Implementing type promotion with Method Overloading (case: method match found)
- Implementing type promotion with Method Overloading (case: method match not found)
- Example-
- Output-
Method Overloading
Method overloading is an object-oriented concept in which a class has many methods with the same name but having different parameters. This will increase the readability of the program. You can overload the methods by either changing the number of arguments used or by changing the data type of the arguments.
Method overloading by changing the number of arguments-
In the below example we are using two add() methods but with a different number of parameters. These methods are static so you do not have to create an instance for these methods.
Example-
Output-
Method overloading using different data types of the arguments-
In the below example we are using two add90 methods but with different data type arguments.
Example-
Output-
Note :
We cannot achieve method overloading if we keep the definition of the method the same including a number of parameters and the data type of the parameters but changing the return type of the methods. This will create ambiguity for the compiler and you will get a compile-time error.
Example-
Output-
Overloading main() method
Yes, it is possible for overloading the main() method. But the main() method with the staring array as arguments will be called by the JVM.
Example-
Output-
Implementing type promotion with Method overloading
If no match for the data type is found then one data type will get promoted to another data type implicitly by JVM. for example- byte can be promoted to short, long, int, double or float. Short data type to int, long, float or double. Char data type to int, long, float or double.
Example-
Output-
Implementing type promotion with Method Overloading (case: method match found)
If the data type of the arguments matches with the parameter data type, then type promotion will not be performed.
Example-
Output-
Implementing type promotion with Method Overloading (case: method match not found)
If there is no match found then the implicit type promotion will not be performed.
Example-
Output-