Method overloading

Our new and interesting topic for today is method overloading. Be careful — method overloading must not be confused with method overriding.

Unlike overriding, overloading is a very simple operation. It actually isn't an operation on methods, though sometimes it is referred to by the terrible term parametric polymorphism.

The issue here is that all methods within a class must have unique names. Well, that's not entirely accurate. Well, more accurately, that's not accurate at all. The method name does not have to be unique. What must be unique is the union of the method name and the types of the method's parameters. This union is known as the method signature

Examples:

Code Description
public void print();
public void print2();
This is allowed. The two methods have unique names.
public void print();
public void print(int n);
And also this. The two methods have unique names (signatures).
public void print(int n, int n2);
public void print(int n);
The methods are still unique
public int print(int a);
public void print(int n);
But this is not allowed. The methods are not unique. Even though they return different types.
public int print(int a, long b);
public long print(long b, int a);
But you can do this. Method parameters are unique

The signature includes the method name and the parameter types. It does not include the method's return type and parameter names. A class cannot have two methods with the same signatures — the compiler won't know which one to call.

The parameter names don't matter, since they get lost during compilation. Once a method is compiled, only its name and parameter types are known. The return type is not lost, but the method's result does not have to be assigned to anything, so it is also not included in the signature.

According to OOP principles, polymorphism is hiding different implementations behind a single interface. When we call the System.out.println() method, for example, different methods are called depending on which arguments are passed. This is polymorphism in action.

That is why different methods with identical names contained in the same class are considered to be a weak form of polymorphism.