Module 3: Interfaces & Abstract Classes (The Contract)
📚 Module 3: Interfaces & Abstract Classes
Focus: Moving from “What it is” to “What it can do.”
In professional Java development, we don’t just build objects; we build Contracts. These ensure that our system works correctly even when we swap parts.
🏗️ Step 1: The Interface (The “Contract”)
An Interface is a list of methods that a class MUST have, but it doesn’t say how to do them.
🧩 The Analogy: The Electrical Outlet
- The wall outlet is an Interface. It says: “If you want power, you must have two prongs of this exact size.”
- The outlet doesn’t care if you plug in a TV, a Toaster, or a Lamp.
- As long as you follow the Contract (the prongs), you get power.
In Java:
public interface Playable {
void play(); // No body, just a definition!
}
public class Mp3Player implements Playable {
public void play() {
System.out.println("Playing audio file...");
}
}🏗️ Step 2: Abstract Classes (The “Half-Built House”)
An Abstract Class is a class that cannot be built on its own. It has some finished parts and some “To-Be-Finished” parts.
🧩 The Analogy: The Cake Mix
- You can’t eat a Cake Mix (Abstract Class). It’s not a cake yet.
- It has some things ready (Flour, Sugar).
- But it says: “You must add eggs and milk to finish this.”
🏗️ Step 3: Why do we use them?
- Decoupling: You can write code that works with
Playableobjects without knowing if it’s an MP3, a Video, or a CD. - Safety: The compiler forces you to finish the “Cake Mix” before you can use it.
🥅 Module 3 Review
- Interface: A strict contract of what a class MUST do.
- Implements: The keyword for following an interface.
- Abstract Class: A partially finished blueprint.
- Extends: The keyword for finishing an abstract class.