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
| Interface | Abstract Class | |
|---|---|---|
| Fields | constants only | any |
| Methods | abstract + default | any |
| Inheritance | multiple | single |
Your Task
Create:
Printableinterface withvoid print()Measurableinterface withdouble measure()and a default methodsummary()returning"Measurement: " + measure()Boximplementing both, with fieldswidth,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.