1. The Hook (The "Byte-Sized" Intro)
In a Nutshell: To implement an interface, a class uses the implements keyword and provides concrete implementations for ALL abstract methods in the interface. A class can implement multiple interfaces, enabling flexible, capability-based design.
Think of certifications. When you get a "Java Certified" badge, you've "implemented" the Java certification interface—you've proven you can do everything the certification requires!
2. Conceptual Clarity (The "Simple" Tier)
💡 The Analogy: The Driver's License
To get a driver's license (implement Drivable):
- You must pass written test (
knowRules()) - You must pass driving test (
drive()) - You must pass vision test (
see())
Once you implement all requirements, you're certified!
3. Technical Mastery (The "Deep Dive")
Formal Definition
Implementing Interface:
- Use
implementskeyword after class name - Provide
publicimplementations for ALL abstract methods - Can implement multiple interfaces:
class C implements A, B, C - Can extend a class AND implement interfaces:
class C extends Parent implements A, B
4. Interactive & Applied Code
interface Printable {
void print();
}
interface Scannable {
void scan();
}
// Implementing multiple interfaces
class AllInOnePrinter implements Printable, Scannable {
@Override
public void print() {
System.out.println("Printing document...");
}
@Override
public void scan() {
System.out.println("Scanning document...");
}
}
// Extending class + implementing interfaces
class Device {
String brand;
Device(String brand) { this.brand = brand; }
}
class SmartPrinter extends Device implements Printable, Scannable {
SmartPrinter(String brand) {
super(brand);
}
@Override
public void print() {
System.out.println(brand + " printing...");
}
@Override
public void scan() {
System.out.println(brand + " scanning...");
}
}
public class Main {
public static void main(String[] args) {
AllInOnePrinter printer = new AllInOnePrinter();
printer.print();
printer.scan();
// Polymorphism
Printable p = printer;
p.print();
Scannable s = printer;
s.scan();
}
}5. The Comparison & Decision Layer
| Scenario | Syntax |
|---|---|
| Implement one | class C implements A |
| Implement multiple | class C implements A, B, C |
| Extend + Implement | class C extends Parent implements A, B |
6. The "Interview Corner" (The Edge)
The "Killer" Interview Question:
"What happens if you don't implement all interface methods?"
Answer: The class must be declared abstract. You can't create a concrete class that doesn't fulfill the interface contract.
Pro-Tip: Use interfaces for dependency injection:
class Service {
private Notifier notifier; // Interface, not concrete class
Service(Notifier notifier) {
this.notifier = notifier; // Inject any implementation!
}
}