Chapter 2 |
Overloading 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 is called overloading. The primary requirement for overloading is that different methods must have different method signatures.
The signature of a method is the name of the method and the data types of its parameters. For example:
myMethod(int, double, String)
Note! The modifier and the return type are not part of the signature. Neither 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
Chapter 2 |