Task 5 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

3.5 Methods — a family of overloads

Lesson

When overloading helps

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.


Worked example

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?


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.


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));
    }
}