/* Author: James Tam Version: Feb. 4, 2021 Learning objectives: 1) Knowing how to define overloaded methods. 2) Understanding how the compiler determines which overloaded method is called at compile-time. (For the benefits or stylistic reasons why overloading is used see the lectures covering the Introduction to Object-Oriented programming). */ public class OverloadExample { public void overloadedMethod(Boolean b) { //! is the logical negation operator System.out.println(b + " becomes " + !(b)); } public void overloadedMethod(double num) { System.out.println(num + " doubled=" + (num*2)); } //Precondition: parameter is a string that consists of a whole number. //Limitation: doesn't check if the precondition is true. (JT: this //limit was included on purpose to avoid introducing new concepts that //students wouldn't have seen yet such as exception handling). public void overloadedMethod(String aString) { System.out.print("$"+ aString + " with your bonus is "); System.out.println("$" + aString + "0"); } public void overloadedMethod(double numerator, double denominator) { if (denominator == 0) { System.out.println("Attemped division by zero"); } else { System.out.print(numerator + "/" + denominator + "="); System.out.println(numerator/denominator); } } //Poor use of overloading. While the compiler can easily distinguish //between badOverload(String,int) vs. badOverload(int,String) it's //easy for a person (the programmer who is calling one of these //methods to mix them up. Don't do this! public void badOverload(String name, int age) { System.out.println(name + " is " + age + " years old."); } public void badOverload(int age, String name) { System.out.println(age + " years young is " + name + "."); } }