Session 2 |
Overloading of methods
Quite often we want to create slight variations of the same method with different parameters. For example, we might have a method multiplyNumbers that allows us to find the multiplication of two numbers:
multiplyNumbers(4,5);
and other times we want to find the square of the number:
multiplyNumbers(4);
Some programming languages require to come up with different names for the methods (e.g. multiplyNumbers and squareNumber). Fortunately Java allows us to have more than one method with the same name as long as they have different parameters. This process is called overloading. The primary requirement for overloading: the different methods have different method signatures.
The signature of a method is the name of the method and the data types of its parameters. Example:
myMethod( int, double, String )
Note! The modifier and the return type are not part of the signature. Either the names of the parameters matter!
Example of method multiplyNumbers overloading (pay attention to the signatures!):
public class MultiplyNumbers{ public static int multiplyNumbers(int a, int b){ return a*b; } public static int multiplyNumbers(int a){ return a*a; } public static void main(String[] args){ System.out.println(multiplyNumbers(3,5)); System.out.println(multiplyNumbers(5)); } }
Self-assessment
Session 2 |