Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Lesson 69

Method Overloading

PRESENTED BY

Keith Vassallo icemalta.com


Overloading
- Overloading methods means creating methods in the same class with the
same name but with different arguments.
- This might seem like a strange idea, but it can actually be very useful.
- Imagine we have a getBMI() method, which must work with both metric and
imperial measurements.
- The metric version accepts two parameters – height (in cm) and weight (in kg)
- The imperial version accepts three parameters – feet, inches and weight (in
lbs).
- What would you call the two methods?
• getImperialBMI and getMetricBMI?

icemalta.com
• getBMI1 and getBMI2?
• getBMIWithFeetAndPounds and getBMIwithCMandKG?
Overloading
With method overloading, both methods can have the same name:

public double getBMI(float height, float weight) {


return weight / (height * height);
}

public double getBMI(int feet, int inches, int lbs) {


int heightInInches = (feet*12)+inches;
return (double) (lbs / (heightInInches * heightInInches)) * 703;
}

- The two methods have the same name, but a different argument list.

icemalta.com
- Java will automatically decide which method to use, based on the
parameters given.
Overloading
Java chooses the method to call.

public double getBMI(float height, float weight) {


return weight / (height * height);
} getBMI(173, 85);
public double getBMI(int feet, int inches, int lbs) { getBMI(5, 8, 187);
int heightInInches = (feet*12)+inches;
return (double) (lbs / (heightInInches * heightInInches)) * 703;
}

icemalta.com
Great work, you’ve completed this lesson!

Next up: Arguments By Reference


and By Value

icemalta.com
© 2011-2017 Institute of Computer Education Ltd.

The contents of this document are copyright to the Institute of Computer Education Ltd, unless otherwise stated, and must not be reproduced without permission.

Every effort has been made to trace all of the copyright holders, but if any have been inadvertently overlooked the Institute of Computer Education Ltd. will be pleased to make the necessary arrangements at the first
opportunity. Please contact us directly. While the Institute of Computer Education Ltd. has taken all reasonable care in the preparation of this work, the Institute of Computer Education Ltd. makes no representation,
express or implied, with regard to the accuracy of the information contained in this work and cannot accept any legal responsibility or liability for any errors or omissions from the work or the consequences thereof.
The reader assumes sole responsibility for the selection of these materials to achieve its intended results. Products and services that are referred to in this work may be either trademarks and/or registered
trademarks of their respective owners. The editors and author/s make no claim to these trademarks. icemalta.com

You might also like