java · level 2 · unit 5 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
An is a promise to have certain methods.
A circle and a square are not related, yet both have an area. An interface lists methods without writing them: interface Shape { double area(); }. That area is an : a name, brackets and a semicolon, but no body.
A class signs the promise with , then writes every listed method, marked public. Miss one and Java refuses to compile. A class can extend only one superclass, but it can implement as many interfaces as it likes.
Now a List<Shape> can hold circles and squares. Here is a secret: List is an interface too, and ArrayList is one class that implements it.
import java.util.*;
public class Main {
interface Shape { double area(); }
static class Square implements Shape {
double side;
Square(double side) { this.side = side; }
public double area() { return side * side; }
}
static class Circle implements Shape {
double radius;
Circle(double radius) { this.radius = radius; }
public double area() { return 3.14 * radius * radius; }
}
public static void main(String[] args) {
List<Shape> shapes = List.of(new Square(3), new Circle(1));
for (Shape shape : shapes) {
System.out.println(shape.area());
}
}
} Methods in an interface are public without saying so, so the class must say public too.
guess first
The band warms up. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.*;
public class Main {
interface Noisy { String noise(); }
static class Drum implements Noisy {
public String noise() { return "Boom"; }
}
static class Bell implements Noisy {
public String noise() { return "Ding"; }
}
public static void main(String[] args) {
List<Noisy> band = List.of(new Bell(), new Drum(), new Bell());
String song = "";
for (Noisy thing : band) {
song = song + thing.noise() + " ";
}
System.out.println(song.trim());
}
}
your turn
Your turn. Sign up a new pet.
On line 11, sign the promise so the hamster counts as a Pet. Give it a name on line 12 and a trick on line 13, then press run.
output
press run to see what happens
fix it
The alarm clock broke its promise. Fix it!
output
press run to see what happens
- Java says
Clock is not abstract and does not override abstract method hour() in Alarmon line 6. Alarmlists two methods, andClockpromised to write both. It only wrotesound.- Add
public int hour() { return 7; }insideClock, after line 7, then press run.
nailed it
your classes keep their promises. :D
- An interface lists methods that a class promises to write.
implementssigns the promise, and each method must bepublic.- A list of an interface type holds any class that signs it.
new words in your collection
- interface
- abstract method
- implements
This lesson isn’t saved. A free account remembers every lesson you finish.