Lesson 11 โข Expert
Interfaces & Abstract Classes
Define contracts and partial blueprints โ the tools that make Java code truly flexible and testable in professional applications.
๐ Before You Start
Make sure you're comfortable with these concepts from earlier lessons:
- Classes & Objects (Lesson 9) โ creating and using classes
- Inheritance (Lesson 10) โ extending classes with
extends - Methods (Lesson 6) โ defining and calling methods
What You'll Learn
- โ What interfaces are โ contracts your classes promise to fulfill
- โ
Implementing interfaces with
implements - โ Abstract classes โ partial blueprints with shared code
- โ Default and static methods in interfaces (Java 8+)
- โ Multiple interface implementation (Java's answer to multiple inheritance)
- โ When to choose abstract classes vs interfaces (with clear rules)
1๏ธโฃ What Are Interfaces?
Real-world analogy: An interface is like a job description. It lists what the employee must be able to do (methods) โ "must be able to write reports, attend meetings, meet deadlines" โ but doesn't specify how they do it. Different employees (classes) fulfill the same job description in their own way.
Why interfaces matter: They allow you to write code that works with any implementation. A sorting function that accepts Comparable works with Strings, Integers, custom objects โ anything that implements the interface.
// Define the contract
interface Drivable {
void drive(); // what must be done
void stop(); // no implementation โ just the signature
int getSpeed();
}
// Fulfill the contract โ must implement ALL methods
class Car implements Drivable {
private int speed = 0;
public void drive() { speed = 60; System.out.println("Car driving"); }
public void stop() { speed = 0; System.out.println("Car stopped"); }
public int getSpeed() { return speed; }
}
class Bicycle implements Drivable {
private int speed = 0;
public void drive() { speed = 15; System.out.println("Pedaling"); }
public void stop() { speed = 0; System.out.println("Braking"); }
public int getSpeed() { return speed; }
}
// Now any method accepting Drivable works with both!
void testDrive(Drivable vehicle) {
vehicle.drive();
System.out.println("Speed: " + vehicle.getSpeed());
vehicle.stop();
}2๏ธโฃ Abstract Classes โ Partial Blueprints
Analogy: An abstract class is like a partially built house. The foundation and framing are done (concrete methods), but you need to choose the paint color and flooring (abstract methods). You can't move into a half-built house (can't instantiate), but it gives every finished house a common structure.
abstract class Shape {
String color; // shared field
Shape(String color) { this.color = color; }
abstract double area(); // MUST be implemented by children
void describe() { // shared implementation โ all shapes get this
System.out.println(color + " shape, area = " +
String.format("%.2f", area()));
}
}
class Circle extends Shape {
double radius;
Circle(String color, double r) { super(color); radius = r; }
double area() { return Math.PI * radius * radius; }
}
class Rectangle extends Shape {
double w, h;
Rectangle(String color, double w, double h) { super(color); this.w = w; this.h = h; }
double area() { return w * h; }
}
// Shape s = new Shape("Red"); // ERROR! Can't instantiate abstract class
Shape s = new Circle("Red", 5);
s.describe(); // "Red shape, area = 78.54" โ polymorphism works!Try It: Interfaces & Polymorphism
See how different classes implement the same interface contract
// ๐ก Try modifying this code and see what happens!
// Java Interfaces & Polymorphism (Simulated)
console.log("=== Interfaces & Polymorphism ===\n");
// Interface simulation โ Drivable contract
console.log("--- Interface: Drivable Contract ---");
class Car {
#speed = 0;
drive() { this.#speed = 60; return "Car driving at " + this.#speed + " mph"; }
stop() { this.#speed = 0; return "Car stopped"; }
getSpeed() { return this.#speed; }
}
class Bicycle {
#speed = 0;
drive()
...3๏ธโฃ Multiple Interfaces & Default Methods
Java doesn't allow multiple inheritance (extending two classes), but a class can implement multiple interfaces. Since Java 8, interfaces can also have default methods with implementations:
interface Flyable {
void fly();
default void land() { System.out.println("Landing safely"); }
}
interface Swimmable {
void swim();
default void dive() { System.out.println("Diving deep"); }
}
// A Duck can do both!
class Duck implements Flyable, Swimmable {
public void fly() { System.out.println("Duck flies"); }
public void swim() { System.out.println("Duck swims"); }
// Inherits default land() and dive() for free!
}
Duck d = new Duck();
d.fly(); d.land(); // from Flyable
d.swim(); d.dive(); // from Swimmable4๏ธโฃ Interface vs Abstract Class โ Decision Guide
| Feature | Interface | Abstract Class |
|---|---|---|
| Methods | Abstract + default | Abstract + concrete |
| Fields | Constants only | Any fields |
| Multiple | โ Implement many | โ Extend one |
| Constructor | โ None | โ Yes |
| When to use | Unrelated classes share behavior | Related classes share code |
Simple rule: Start with an interface. Only switch to abstract class when you need shared state (fields) or constructors.
Try It: Abstract Class Shape Hierarchy
Build a shape system with abstract classes and polymorphism
// ๐ก Try modifying this code and see what happens!
// Abstract Class Shape Hierarchy (Simulated)
console.log("=== Abstract Class Hierarchy ===\n");
class Shape {
constructor(color) {
this.color = color;
if (new.target === Shape) throw new Error("Can't instantiate abstract class!");
}
area() { throw new Error("Must implement area()!"); }
perimeter() { throw new Error("Must implement perimeter()!"); }
describe() {
return this.color + " " + this.constru
...5๏ธโฃ Real-World Interface Examples
Comparable<T> โ lets objects be sorted: Collections.sort(list)
Serializable โ marks objects that can be saved to files or sent over network
Iterable<T> โ allows objects to work in for-each loops
Runnable โ defines code that can run in a thread
Every Java framework you'll ever use โ Spring, Android, Jakarta EE โ is built on interfaces. Learning them well now pays off enormously later.
6๏ธโฃ Common Beginner Mistakes
โ Mistake 1: Using abstract class when interface would suffice
If there's no shared state or code, use an interface. It's more flexible โ classes can implement many interfaces but only extend one class.
โ Mistake 2: Forgetting to implement ALL interface methods
If your class says implements Drivable, it must provide implementations for every abstract method โ or itself be declared abstract.
โ Mistake 3: Not making interface methods public
Interface methods are implicitly public abstract. When you implement them, you must declare them public โ a lower access modifier won't compile.
Try It: Payment System with Interfaces
Build a real-world payment processing system using interface contracts
// ๐ก Try modifying this code and see what happens!
// Practical Payment System (Simulated)
console.log("=== Payment System with Interfaces ===\n");
// Multiple interfaces โ Payable + Refundable
class CreditCard {
constructor(number) { this.number = "****" + number.slice(-4); }
pay(amount) { return "๐ณ Charged $" + amount.toFixed(2) + " to card " + this.number; }
refund(amount) { return "โฉ๏ธ Refunded $" + amount.toFixed(2) + " to card " + this.number; }
}
class PayPal {
construc
...๐ Quick Reference
| Keyword | Syntax | Purpose |
|---|---|---|
| interface | interface Drivable { } | Define contract |
| implements | class Car implements Drivable | Fulfill contract |
| abstract class | abstract class Shape | Partial blueprint |
| abstract method | abstract double area(); | Must be implemented |
| default | default void log() { } | Interface default method |
| multi-impl | implements A, B, C | Multiple interfaces |
๐ Lesson Complete!
You now understand interfaces, abstract classes, default methods, and when to use each โ essential tools for designing flexible, maintainable Java systems that can evolve over time.
Next up: Exception Handling โ handle errors gracefully with try-catch and never let your program crash unexpectedly.
Sign up for free to track which lessons you've completed and get learning reminders.