Abstract Classes vs Interfaces

Abstract Classes vs Interfaces

Both abstract classes and interfaces are core abstraction mechanisms in Java, but they serve distinct architectural roles.

Abstract Classes: What Something IS

An abstract class is an incomplete blueprint that cannot be instantiated directly with new.

  • Can maintain instance variables (state).
  • Can contain both abstract methods (without bodies) and concrete methods (with implementations).
  • A concrete subclass must implement all inherited abstract methods.
public abstract class Shape {
    protected String color;

    public Shape(String color) {
        this.color = color;
    }

    public abstract double calculateArea();
}

Interfaces: What Something CAN DO

An interface establishes a behavioral contract or specification that any implementing class promises to satisfy.

  • A class can implement multiple interfaces (implements Drawable, Serializable).
  • Represents capabilities or roles rather than ontological taxonomy.
public interface Drawable {
    void draw();
}

Summary Comparison Table

| Dimension | Abstract Class | Interface | |---|---|---| | Multiple Inheritance | No (extends only one) | Yes (implements many) | | Instance State | Allowed (private int x;) | No instance state | | Relationship | IS-A (Dog IS-A Animal) | CAN-DO (Bird CAN Fly) |

Exercise 1
Question

Why can an interface represent "CAN-DO" behavior across completely unrelated hierarchies?

Show solution ↓
Solution

Because interfaces define pure capabilities (Comparable, AutoCloseable, Flyable) without assuming common ancestry, allowing disparate classes (Plane, Duck) to share the same polymorphic contract.