Course contentsShow
← Java
Lesson 486 of 2,87012. Abstract Classes and InterfacesFree lesson

When to Use Abstract Classes

Identifying use cases for abstract classes: partial implementation, shared state, and is-a relationships with common behavior.

When to Use Abstract Classes

You'll learn how to recognize the situations where abstract classes are the right design choice.

Core Idea

Abstract classes solve a specific design problem: you have a group of related classes that share some common implementation and behavior, but each class also needs to customize certain parts. If you find yourself writing classes where the is-a relationship holds strongly, partial code can be reused, and subclasses need shared state, an abstract class is often the perfect fit.

Three Key Scenarios

1. Partial Implementation

When you have methods that should work the same way across all subclasses, but other methods must be customized. You implement the shared logic once in the abstract class and leave only the variable parts abstract.

Example: An Animal abstract class might implement a complete sleep() method (all animals sleep similarly), but leave makeSound() abstract (each animal sounds different).

2. Shared State (Fields)

When subclasses need to inherit and share instance variables. Interfaces cannot declare instance fields, but abstract classes can.

Example: All Vehicle subclasses share speed, fuelLevel, and position fields that are initialized by the abstract parent's constructor.

3. Is-a Relationships with Common Behavior

When you have a clear inheritance hierarchy where each subclass truly "is a" more specific version of the parent, and they share foundational behavior.

Example: Dog, Cat, and Bird are all Animal. They share fields like age and name, concrete methods like eat(), but each implements makeSound() differently.

The Litmus Test

Ask yourself: "Do my classes share both behavior and state, with some methods needing customization?" If yes, use an abstract class. If they only share method signatures with no shared implementation, an interface (which you'll learn next) might be better.

Key Takeaway: Use abstract classes when you need partial implementation, shared instance variables, and a strong is-a relationship with common behavior across subclasses.