Objects and Classes
Object
Overload methods
How to overload methods
- When two or more methods have the same name but different parameter lists, the methods are overloaded.
- It's common to use overloaded methods to provide two or more versions of a method that work with different data types or that supply default values for omitted parameters.
Example 1: A method that accepts one argument
public void printToConsole(String sep) { System.out.println(code + sep + description + sep + price); }
Example 2: An overloaded method that provides a default value
public void printToConsole() { printToConsole("|"); // this calls the method in example 1 }
Example 3: An overloaded method with two arguments
public void printToConsole(String sep, boolean printLineAfter) { printToConsole(sep); // this calls the method in example 1 if (printLineAfter) System.out.println(); }
Code that calls the PrintToConsole methods
Product p = ProductDB.getProduct("java"); p.printToConsole(); p.printToConsole(" ", true); p.printToConsole(" ");
The console
java|Murach's Beginning Java 2|49.5 java Murach's Beginning Java 2 49.5 java Murach's Beginning Java 2 49.5