Instructional Material: Overloading

Printer-friendly version

Remember that we mentioned that a method's name and parameter list are called the method's signature and this signature is how Java identifies methods. So it follows that while methods with a different name are definitely not the same method, methods with the same name and different parameter lists are also not the same method. This allows you to use different parameter lists to create variations of a method single name. This is called overloading. Here is an example of overloading:

The calling code can call square() with a double or an integer and the correct method for the parameter data type will be used. Here is an example showing varying the number of parameters:

Calling code can use either method but the second has the option to return the area in meters. Note that the second method reuses the first method so that the basic area computation is only defined in one place. In effect, the second method "adds to" or "overloads" the functionality of the first.

Here is this example in CodingGround. Add new methods to compute volume (with and without the meters option) if a height parameter is supplied. In your new methods, reuse the computeArea() method.

 

Material Type: 
Lecture/Presentation
Education Level: 
HW Platform: 
SW Platform: 
Interactivity Style: 
Audience: