Java Interfaces
An interface is a promise: any class that implements it must provide its methods. A class can implement many interfaces.
ExampleJava
public class Main {
interface Shape {
double area();
}
static class Circle implements Shape {
double r;
Circle(double r) { this.r = r; }
public double area() { return Math.PI * r * r; }
}
static class Rect implements Shape {
double w, h;
Rect(double w, double h) { this.w = w; this.h = h; }
public double area() { return w * h; }
}
public static void main(String[] args) {
Shape[] shapes = { new Circle(1), new Rect(2, 3) };
for (Shape s : shapes) {
System.out.printf("%.2f%n", s.area());
}
}
}Output
3.14 6.00
Quick check
What must a class do when it implements an interface?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.