"Hello, Amigo! I'm going to tell you about method overloading."
"You can overload them too?! What a day!"
"You can do a lot with them, but we won't go into that right now."
"It's a deal."
"Overloading is a very simple operation. Actually, it's not even an operation on methods, though it is sometimes referred to by a frightening name: parametric polymorphism."
The thing you must remember is that every method in a class must have a unique name.
"Yeah, I know."
"Well, that's not entirely true. I mean, it's not at all true. A method does not have to have a unique name. What must be unique is the combination of a method name and the types of its parameters. This combination is also known as a method signature."
Code | Comments |
---|---|
|
This is allowed. The two methods have unique names. |
|
And this is also allowed. The two methods have unique names (signatures). |
|
The method names are still unique here. |
|
But this is not allowed. The methods are not unique, even though different types are being passed. |
|
But this is allowed. The method parameters are unique. |
"I've already seen that somewhere."
"Yep. When you type "System.out.println", IntelliJ IDEA suggests a couple dozen versions of print methods that use different parameters. The compiler simply identifies and then calls the required method based on the types of the parameters you pass."
"That's not so difficult. But it's not polymorphism."
"Or more accurately, it's not method overriding."
By the way, I want to point out that the parameter names are irrelevant. They are lost during compilation. Once a method is compiled, only its name and parameter types are known.
GO TO FULL VERSION