Method Overloading

When you give two or more methods the same name within the same class you are overloading the method name.

Overloaded methods have something different in their parameter lists.

Java distinguishes overloaded methods according to the number of parameters/and/or the types of parameters.

If there is no perfect match of parameters, Java will try simple type conversions (only smaller to bigger data type so that information is not lost), for example, casting an int into a double, to see whether that produces a match.

This can be applied to void methods, to methods that return a value, to static methods, to non-static methods, and also constructors.

Overloaded methods can cause ambiguous invocation which would lead to compile errors.

E.g of ambiguous overloading

Method 1

public int max(int x, double y)
/// code

Method 2

public int max(double x, int y)
/// code

If we call


the first argument is a double and second is an int, so Method 2 would be called.

If we call


Method 1 would be called.

However, if we call


we have two Ints;

Will 3 be converted to a double so calling method 2 or
Will 5 be converted to a double so calling method 1?

This is AMBIGUOUS and will cause a runtime error. Both methods could be called and the compiler is not sure.

To solver this, we need to create another method that takes two Ints.

Method 3

public int max(int x, int y)
/// code

Leave a Reply