🎯 What you will learn
- Declare an interface
- Implement it in classes
- Program to an interface, not a class
👋 Let’s get started!
An interface is a promise 🤝: “any class that implements me WILL have these methods.” A Drone and a Bird are very different, but both can promise to fly().
🪜 Step by step
1. 📜 Declare
An interface lists method signatures.
interface Flyer {
void fly();
}
2. 🤝 Implement
Classes promise to provide the methods.
class Drone implements Flyer {
public void fly() { System.out.println("Drone buzzes up 🚁"); }
}
class Bird implements Flyer {
public void fly() { System.out.println("Bird flaps wings 🐦"); }
}
3. 🔌 Use the interface type
Code that uses Flyer works with anything that can fly.
Flyer[] flyers = { new Drone(), new Bird() };
for (Flyer f : flyers) f.fly();
🧪 Try it!
Read the code, guess what it prints, then press 👀 Show output.
Sound makers
interface SoundMaker { String play(); }
class Drum implements SoundMaker { public String play() { return "Boom 🥁"; } }
class Guitar implements SoundMaker { public String play() { return "Strum 🎸"; } }
// main:
SoundMaker[] band = { new Drum(), new Guitar(), new Drum() };
for (SoundMaker s : band) System.out.println(s.play());Implement Printable
interface Printable {
void print();
}
class Ticket implements Printable {
public void print() { System.out.println("🎟️"); }
}📖 Key words
Tap a card to flip it over!
- Interface
- A contract of methods 📜
- implements
- Promises to follow an interface 🤝
- Abstract
- Declared but not yet filled in 🫥
- Contract
- Rules a class agrees to 📝
🏆 Challenge
Predict the output.
Challenge
interface Greeter { String hi(); }
class English implements Greeter { public String hi() { return "Hello"; } }
class Spanish implements Greeter { public String hi() { return "Hola"; } }
// main:
Greeter g = new Spanish();
System.out.println(g.hi() + "!");Knowledge Check Quiz
- What keyword does a class use to follow an interface?
- Can different classes implement the same interface?
- An interface is like…