Skip to content
UPEEC

Interfaces and Abstract Classes

Define contracts with interfaces and share partial implementations with abstract classes.

Intermediate
Comments 0
interface Sensor {
    double read();
    default String unit() { return ""; }      // default method (Java 8+)
}

abstract class AnalogSensor implements Sensor {
    protected int pin;
    public abstract double calibrate(int raw);
    public double read() { return calibrate(analogRead(pin)); }
}

Use an interface for "can do" capabilities (Comparable, Runnable) and an abstract class when related classes share state and code.

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.