O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.6. Method Overloading

Java allows you to define several methods in a class with the same name, as long as each method has a unique set of parameters. Defining two or more methods with the same name in a class is called method overloading.

The name of a method together with the types and sequence of the parameters form the signature of the method; the signature of each method in a class must be distinct to allow the compiler to determine exactly which method you are calling at any particular point. The return type has no effect on the signature of a method. You cannot differentiate between two methods just by the return type. This is because the return type is not necessarily apparent when you call a method. For example, suppose you write a statement such as:

Math.round(value);

Although the preceding statement is pointless since it discards the value that the round() method produces, it does illustrate why the return type cannot be part of the signature for a method. The compiler has no way to know from this statement what the return type of the method round() is supposed to be. Thus, if there were several different versions of the method round(), and the return type were the only distinguishing aspect of the method signature, the compiler would be unable to determine which version of round() you wanted to use.

You will find many circumstances where it is convenient to use method overloading. You have already seen that the Math class contains two versions of the method round() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required