Today we’re going to take a look at overloading in Java.
I really don’t understand why they call this overloading, but it’s essentially exactly what we talked about yesterday with constructors. You can define multiple methods with the exact same name within a class, each with a unique set of accepted parameters that make the method distinguishable.
Just like last time, all of this code is available in my github repo.
This is relatively straight forward, but we can end up doing some neat stuff like the chaining that we did with constructors. Let’s take a look at a new
Flight class that I have created:
Here you can see we end up with five instances of the
add1Passener method. The first three methods we define each provide some new level of functionality, which we’re able to build off of in each of the next methods.
The following two methods are really wrappers for our
Passenger objects. We could have used the existing
add1Passenger methods, but we’re able to provide an extra level of functionality specifically to
Passengers by wrapping our functionality to handle them.
Like I said, this is all pretty straight forward. The parameters that you include in the method call will determine the method that is used.
One other thing to mention is that a best effort will be made to pick the correct method when the included parameters don’t quite match what’s been defined.
Say for example you have a method that accepts a double, but you pass it in an int. Since an int can be expanded out to a double, it can be interpreted and access that method.
However, if you were to try to go the other way with it, and pass a double to something that takes an int, it won’t automatically make this downsizing conversion for you. That’s something you’ll have to specify yourself.