Skip to content

Interfaces (course memo)

Java. The more abstractly code is written, the more reusable it is — you can focus on what you want to achieve without caring about how it's done.

Creating an interface

java
public interface Vehicle {
    double getMaxSpeed();

    void start();
    void stop();
}
  • public interface followed by the name.
  • Every method is implicitly public — no need to write the keyword.
  • Method signatures as usual, but a ; instead of a body — the what, not the how.

Using an interface

java
public class Car implements Vehicle {

    @Override
    public double getMaxSpeed() {
        return 220;
    }

    @Override
    public void start() {
        System.out.println("Starting car engine...");
    }

    @Override
    public void stop() {
        System.out.println("Stopping car engine...");
    }
}
  • A class uses implements InterfaceName and must provide bodies for (at least) the interface's methods.
  • @Override marks that a method is replacing/fulfilling one declared elsewhere (the interface here).

Why it's useful

java
Car firstCar = new Car();

// Car is also a Vehicle:
Vehicle secondCar = new Car();

// Truck is also a Vehicle:
Vehicle truck = new Truck();

// Vehicle can be used anywhere a class could be used:
List<Vehicle> vehicles = List.of(firstCar, secondCar, truck);
for (Vehicle vehicle : vehicles) {
    vehicle.start();
    System.out.println(vehicle.getMaxSpeed());
    vehicle.stop();
}
  • An object is created from its concrete class, but referenced through the interface type.
  • Code working with the Vehicle type doesn't need to know which concrete class it's dealing with, or how each one implements start()/stop()/getMaxSpeed() — only that each guarantees those methods exist and do what they're supposed to.