Better Programming

Advice for programmers.

Follow publication

Member-only story

When to Use Abstract Classes

Dave Taubler
Better Programming
Published in
8 min readJan 7, 2020

Photo by Hikersbay Hikersbay on Unsplash

Abstract classes are a core feature of many object-oriented languages, such as Java.

Perhaps, for that reason, they tend to be overused and misused. Indeed, discussions abound about the overuse of inheritance in OO languages, and inheritance is core to using abstract classes.

In this article, we’ll use some examples of patterns and anti-patterns to illustrate when to use abstract methods, and when not to.

While this article presents the topic from a Java perspective, it is also relevant to most other object-oriented languages, even those without the concept of abstract classes.

To that end, let’s quickly define abstract classes. If you already know what abstract classes are, feel free to skip the following section.

Defining Abstract Classes

Technically speaking, an abstract class is a class that cannot be directly instantiated. Instead, it is designed to be extended by concrete classes that can be instantiated.

Abstract classes can — and typically do — define one or more abstract methods, that themselves do not contain a body. Instead, concrete subclasses are required to implement the abstract methods.

Let’s fabricate a quick example:

public abstract class Base {    public void doSomething() {
System.out.println("Doing something...")
}
public abstract void doSomethingElse();}

Note that doSomething(), a non-abstract method, has implemented a body, while doSomethingElse(), an abstract method, has not. You cannot directly instantiate an instance of Base. Try this, and your compiler will complain:

Base b = new Base();

Instead, you need to subclass Base like so:

public class Sub extends Base {    public abstract void doSomethingElse() {
System.out.println("Doin' something else!");
}
}

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Dave Taubler
Dave Taubler

Written by Dave Taubler

Software architect, engineering leader, musician, husband, dad

Responses (1)

Write a response