Unit 13: Overloading
After reading this unit, students should
- understand what is overloading
- understand how to create overloaded methods
Method overloading
In the previous unit, we introduced method overriding. That is, when a subclass defines an instance method with the same method descriptor as an instance method in the parent class.
In contrast, method overloading is when we have two or more methods in the same class with the same name but a differing method signature1. In other words, we create an overloaded method by changing the type, order, and number of parameters of the method but keeping the method name identical.
Lets consider an add
method which allows us to add two numbers, and returns the result. What if we would like to create an add
method to sum up three numbers?
1 2 3 4 5 6 7 |
|
In the example above, the methods add(int, int)
and add(int, int, int)
are overloaded. They have the same name but a different number of parameters. We can see that this allows us to write methods to handle differing inputs.
Now lets consider our Circle
class again. Our Circle::contains(Point)
method allows us to check if a Point
is within the radius of the current instance of the Circle
. We would like to create a new method Circle::contains(double, double)
which will allow us to check if an x
and y
co-ordinate (another valid representation of a point) is within our circle.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
Circle::contains(Point)
and Circle::contains(double, double)
are overloaded methods.
Recall that overloading requires changing the order, number, and/or type of parameters and says nothing about the names of the parameters. Consider the example below, where we have two contains
methods in which we swap parameter names.
1 2 3 4 5 6 7 8 9 |
|
These two methods have the same method signature, and therefore contains(double, double)
and contains(double, double)
are not distinct methods. They are not overloaded, and therefore this above example will not compile.
As it is also a method, it is possible to overload the class constructor as well. As in the example below, we can see an overloaded constructor which gives us a handy way to instantiate a Circle
object that is the unit circle.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
1 2 3 4 |
|
It is also possible to overload static
class methods in the same way as instance methods. In the next unit, we will see how Java chooses which method implementation to execute when a method is invoked.
-
Note that this is not the same as the method descriptor. You can not overload a method by changing the return type. ↩