Lesson 11 of 20

Interfaces

Interfaces

An interface defines a contract — a set of methods a class must implement:

interface Drawable {
    void draw();                    // abstract method
    default String color() {        // default method (Java 8+)
        return "black";
    }
}

class Circle implements Drawable {
    @Override
    public void draw() {
        System.out.println("Drawing a circle");
    }
}

Multiple Interfaces

A class can implement multiple interfaces (unlike extends):

class Square implements Drawable, Resizable {
    // must implement all abstract methods from both
}

Interface vs Abstract Class

InterfaceAbstract Class
Fieldsconstants onlyany
Methodsabstract + defaultany
Inheritancemultiplesingle

Your Task

Create:

  • Printable interface with void print()
  • Measurable interface with double measure() and a default method summary() returning "Measurement: " + measure()
  • Box implementing both, with fields width, height, depth

Create Box(2.0, 3.0, 4.0), call print(), measure(), and summary().

TeaVM (WASM) loading...
Loading...
Click "Run" to execute your code.