Abstract Classes: Is-A with Shared Implementation
What you'll learn: When abstract classes are the right choice for modeling hierarchies where subclasses share both common behavior and state.
The Core Idea
You've learned that abstract classes can hold both abstract methods (the contract) and concrete methods (the implementation). But their real power emerges when you need to model an is-a relationship where multiple subclasses share both behavior and internal state.
Think of it this way: if you're designing a family of related classes that all need the same set of fields and some common method implementations, an abstract class is your tool. Unlike interfaces (which until recently couldn't hold state), abstract classes can provide a shared foundation that all subclasses inherit.
When to Prefer Abstract Classes
Choose an abstract class when:
- Shared state is essential — Subclasses need common fields (instance variables)
- Partial implementation helps — Some methods can be fully implemented once for all subclasses
- The hierarchy is cohesive — All subclasses truly represent specialized versions of the same concept
- Protected access matters — You need to share helper methods or fields that shouldn't be public
Example scenario: Imagine modeling Animal with shared fields like age and weight, and a concrete method grow() that all animals use. Subclasses like Dog and Cat add their own specialized behavior, but inherit the common state and growth logic.
The Is-A Test Still Applies
Abstract classes enforce the is-a relationship just like concrete inheritance. Every instance of your subclass is-an instance of the abstract parent. This means you can use polymorphic references and substitutability still holds.
Key Takeaway: Use abstract classes when modeling is-a hierarchies where subclasses need to share both common state (fields) and partial implementation, creating a reusable foundation across related types.