Lesson 5 of 10
Methods and overloading
- 12 min
- 6 checks
- 3 hints
- Go to task
Goal
Return values and methods that share a name
Explanation
The first line of a method states the type of value it returns, then its name, then the type of each parameter, as in static int heal(int hp, int amount), and a method that returns nothing has the return type void. The name together with the parameter types is the method's signature. return ends the method immediately and hands back its value, and if a method has a return type, the compiler rejects it when it might finish without a return.
Overloading means writing several methods with the same name whose parameters differ in number or type. The compiler picks the right version based on what you pass, so max(3, 9) calls the int version and max(2.5, 1.5) calls the double version. Java has no default parameter values, so overloading fills that role: heal(hp) calls heal(hp, 25), and the logic stays in one place.
Keep in mind that Java passes the method a copy of the value, so changing hp inside the method doesn't change the caller's variable. That means heal(hp, 30); on its own computes the result and then throws it away, so store what it returns: hp = heal(hp, 30);.
Your task
Complete three versions of max: the first for two integers, the second for two decimals, and the third for three integers, built on the two-number version. Then complete heal(hp, amount) to return the health after healing without going over 100, and heal(hp) to heal 25 by calling the first version. Finally, fix main so it prints HP: 100.
Checks
6 checks- max works with two integers
- max has a separate version for two decimals
- max works with three numbers
- heal adds health and never goes over 100
- heal with no amount heals 25
- "HP: 100" was printed