0/30 Days Completed 0 Learning Days
Day 22 of 30 · Week 4 — OOPs Through Java
Interfaces
1 Learn
An interface is a contract: it lists methods a class promises to provide. A class uses implements to sign the contract.
A class can extend one class but implement many interfaces. Interfaces are great for unrelated classes that share an ability, like Printable.
2 See the Code
Java
interface Playable {
void play();
}
class Guitar implements Playable {
public void play() { System.out.println("Strum strum"); }
}
class Drum implements Playable {
public void play() { System.out.println("Boom boom"); }
}
public class Band {
public static void main(String[] args) {
Playable[] items = { new Guitar(), new Drum() };
for (Playable p : items) {
p.play();
}
}
}- Playable declares play(); both classes implement it.
- Interface methods are public, so the implementing methods must be public too.
- An array of Playable can hold any class that implements it.
Output
Strum strum Boom boom
3 Practice
- Create an interface Shape with double area(), and implement it in Square and Rectangle.
Try it in your own Java setup or write it in the Practice Notebook.
4 Quick Check
1. Which keyword does a class use with an interface?
2. How many interfaces can a class implement?
Step 5
Answer and check the Quick Check above to unlock this.