Task 1 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 →

8.4 Choosing — interface or abstract class?

Lesson

Two ways to share a type

Both let different classes be treated through one type, but they answer different questions. An abstract class says what a thing is and can carry state (fields), constructors, and shared code. An interface says what a thing can do — a contract with no state. Rule of thumb: use an abstract class when the classes are naturally related and share code; use an interface when unrelated classes must share a capability.


The decisive rule

A class can extends only one class, but can implements as many interfaces as it likes — and it can do both at once:

class Rect extends Shape implements Printable { ... }   // one class, one interface
class C extends A, B { }   // ERROR: cannot extend two classes

So inheritance is your single "is-a" slot; interfaces are unlimited "can-do" labels.


▶ Try it: run this — Rect inherits from Shape and also fulfills Printable.



How many classes can a Java class extend?


How many interfaces can a class implement?


Unrelated classes must share a capability but no code. Use...


Related classes share fields and finished methods. Use...


True or false?


Type exactly what this program prints.

interface Printable {
    String label();
}

abstract class Shape {
    public abstract double area();
}

class Box extends Shape implements Printable {
    private double s;

    public Box(double s) {
        this.s = s;
    }

    public double area() {
        return s * s;
    }

    public String label() {
        return "[box]";
    }
}

public class Main {
    public static void main(String[] args) {
        Box b = new Box(3);
        System.out.println(b.area());
        System.out.println(b.label());
    }
}