Overloading shines when several methods do the same kind of job for different inputs. Giving them one name keeps the idea together and is easier to remember. A classic example is area: a square needs one number, a rectangle needs two.
area
int area(int side) { return side * side; // square } int area(int w, int h) { return w * h; // rectangle } System.out.println(area(5)); // 25 (square) System.out.println(area(4, 3)); // 12 (rectangle)
▶ Try it: both area overloads are defined for you — one argument means a square, two means a rectangle. Run this, then change the numbers and re-run.
area(int side) returns side * side; area(int w, int h) returns w * h. What does area(4, 3) return?
area(int side)
side * side
area(int w, int h)
w * h
area(4, 3)
Why is overloading area useful here?
A method print(int n) already exists. Sort each new method by whether it is a valid overload of it or clashes with it.
print(int n)
True or false?
Type exactly what this program prints.
public class Main { static int box(int s) { return s * s * s; } static int box(int a, int b, int c) { return a * b * c; } public static void main(String[] args) { System.out.println(box(2)); System.out.println(box(2, 3, 4)); } }