Java Abstract Classes and Abstract Methods
Learn when and how to use abstract classes in Java: declaring abstract methods as placeholders, mixing fields and concrete methods, why abstract classes can't be instantiated, abstract variables referring to concrete subclasses, the template method pattern, and abstract classes versus interfaces.
kvi5hnuCode Sprout team member7 min readOn this page
The higher a class sits in a hierarchy, the more general it is. Near the top you often find classes that exist only to give their subclasses a common shape; nobody ever wants an object of exactly that class. Java lets you say so with the keyword abstract.
A Superclass Nobody Instantiates: MediaItem
Picture a small media library that lends out books and podcasts. Both have a title, and both need a one-line summary for the catalog:
a book by Lin Wei, 320 pages
a podcast with 48 episodes
The title is identical for every kind of item, so it belongs in a shared superclass, MediaItem, together with getTitle(). The summary is different: Book and Podcast each know how to build theirs, but a bare MediaItem has nothing sensible to say. Returning an empty string would hide mistakes. Instead, declare the method without a body and mark it abstract:
public abstract String summary(); // subclasses must supply the body
Once a class contains an abstract method, the class itself must be declared abstract:
public abstract class MediaItem {
. . .
public abstract String summary();
}

Abstract Classes Can Have State and Behavior
"Abstract" doesn't mean "empty". An abstract class may declare fields, constructors and fully implemented methods alongside its abstract ones. MediaItem keeps the title and provides its getter:
public abstract class MediaItem {
private final String title;
public MediaItem(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public abstract String summary();
}
An abstract method is a promise that a subclass will fill in. A subclass of an abstract class has two options:
- Implement every inherited abstract method. The subclass is then concrete, and you can create objects of it.
- Leave at least one unimplemented. Then the subclass must be declared
abstractas well.
Forgetting one in a class not marked abstract is a compile error:
error: Audiobook is not abstract and does not override abstract method summary() in MediaItem
You may also mark a class abstract when it has no abstract methods at all, purely to forbid new on it. A few combinations are illegal: an abstract method can't have a body (abstract methods cannot have a body), and it can't also be private, static or final, since each of those would stop a subclass from ever overriding it.
Abstract Classes Can't Be Instantiated
The compiler refuses to create an object of an abstract class:
new MediaItem("Untitled") // error: MediaItem is abstract; cannot be instantiated
Variables of an abstract type are perfectly fine, though. They simply always point at an object of some concrete subclass:
MediaItem m = new Podcast("Night Sky", 48);
A Concrete Subclass: Podcast
public class Podcast extends MediaItem {
private final int episodes;
public Podcast(String title, int episodes) {
super(title); // the superclass stores the title
this.episodes = episodes;
}
@Override
public String summary() {
return "a podcast with " + episodes + " episodes";
}
}
Podcast implements the only abstract method it inherits, so it is concrete.
Putting It Together
The program stores a book and a podcast in a MediaItem[] and prints each one's title and summary:
public class Solution {
public static void main(String[] args) {
MediaItem[] catalog = {
new Book("Rivers of Glass", "Lin Wei", 320),
new Podcast("Night Sky", 48)
};
for (MediaItem m : catalog) {
System.out.println(m.getTitle() + ": " + m.summary());
}
// template method: the abstract class fixes the algorithm, subclasses fill in a step
Report r = new CsvReport();
System.out.print(r.render(new String[] {"Ada", "Linus"}));
}
}
abstract class MediaItem {
private final String title;
public MediaItem(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public abstract String summary();
}
class Book extends MediaItem {
private final String author;
private final int pages;
public Book(String title, String author, int pages) {
super(title);
this.author = author;
this.pages = pages;
}
@Override
public String summary() {
return "a book by " + author + ", " + pages + " pages";
}
}
class Podcast extends MediaItem {
private final int episodes;
public Podcast(String title, int episodes) {
super(title);
this.episodes = episodes;
}
@Override
public String summary() {
return "a podcast with " + episodes + " episodes";
}
}
abstract class Report {
public final String render(String[] rows) { // the template method
var sb = new StringBuilder(header());
for (String row : rows) sb.append(formatRow(row));
return sb.toString();
}
protected String header() { return ""; } // optional hook with a default
protected abstract String formatRow(String row); // required step
}
class CsvReport extends Report {
@Override protected String header() { return "name\n"; }
@Override protected String formatRow(String row) { return row + "\n"; }
}
Rivers of Glass: a book by Lin Wei, 320 pages
Night Sky: a podcast with 48 episodes
name
Ada
Linus
m.summary() may look like a call to a method that has no body. It never is: no object of class MediaItem can exist, so m always refers to a Book or a Podcast, and dynamic binding runs that class's implementation.
Why declare summary() in MediaItem at all, instead of only in the subclasses? Because the compiler only allows calls to methods that the variable's declared type has. Without the abstract declaration, m.summary() wouldn't compile. The abstract method is what makes the polymorphic call legal.
The Template Method Pattern
Abstract classes shine when a superclass defines an algorithm and subclasses supply the steps. In the Report class above, the public final method render fixes the overall process. It calls the protected hook header() (with a default) and the abstract step formatRow (which subclasses must implement). This is the template method design pattern, and the JDK uses it widely. For example, java.util.AbstractList implements most List methods on top of two abstract ones, get(int) and size(). Writing your own list then requires only those two:
List<Integer> squares = new AbstractList<>() {
public Integer get(int i) { return i * i; }
public int size() { return 10; }
};
// squares.contains(49), squares.indexOf(81), squares.subList(2, 5), ... all work
(The new AbstractList<>() { ... } syntax creates an anonymous subclass, covered in the inner classes article.)
Abstract Classes and Interfaces
You'll encounter abstract methods most often inside interfaces, which are the topic of the next part. Here's a preview of how they compare:
| Abstract class | Interface | |
|---|---|---|
| Instance fields (state) | Yes | No (only constants) |
| Constructors | Yes | No |
| Concrete methods | Yes | Yes, as default, static and private methods |
| A class can extend/implement | one | many |
| Typical use | Share state and code in a hierarchy of closely related classes | Define a capability or contract that unrelated classes can have (Comparable, Runnable) |
Modern Java code favors interfaces for types and uses abstract classes mainly to share implementation, often as a "skeletal implementation" of an interface (like AbstractList for List). For closed hierarchies where all subclasses are known, sealed classes and interfaces (coming soon) are another option.
Common questions
Can an abstract class have a constructor?
Yes, and it often should, to initialise its own fields. You can't call it with new directly. Subclass constructors call it through super(...). Making it protected documents that it exists only for subclasses.
Abstract class or interface?
Prefer an interface for defining a type, because a class can implement many interfaces but extend only one class. Use an abstract class when subclasses need shared state (fields) or constructors, or as a skeletal implementation of an interface, like AbstractList for List.
Can an abstract class implement an interface without implementing its methods?
Yes. The abstract class can leave interface methods unimplemented, and the first concrete subclass must implement them. That is how skeletal implementations such as AbstractCollection work.
Can I create an anonymous instance of an abstract class?
Yes: new MediaItem("Demo") { public String summary() { return "a one-off item"; } } creates an anonymous concrete subclass on the spot. For interfaces with one abstract method, a lambda is usually neater.
Is an abstract class with no abstract methods useful?
Sometimes. It prevents direct instantiation of a base class that only makes sense through subclasses. For utility classes with only static methods, use a final class with a private constructor instead.
Summary
- An abstract method is declared without a body:
public abstract String summary();. Any class with an abstract method must be declared abstract. - Abstract classes can have fields, constructors and concrete methods. Put common code there.
- Abstract classes can't be instantiated, but variables of abstract types can refer to objects of concrete subclasses.
- A subclass either implements all abstract methods (becoming concrete) or is itself abstract.
- Declaring the abstract method in the superclass enables polymorphic calls such as
m.summary(). - The template method pattern uses an abstract class to fix an algorithm and let subclasses supply steps.
- Interfaces are often the better choice for types; abstract classes are best for sharing state and implementation.
Practice Questions
Can an abstract class have a constructor, even though you can't instantiate it? What is it for?
Yes. Subclass constructors call it with super(...) to initialize the fields the abstract class declares, like title in MediaItem.
Shape is abstract with abstract double area(). Which of these compile: Shape s = new Shape(); Shape s = new Circle(2); Shape[] shapes = new Shape[10];
new Shape() doesn't compile, since abstract classes can't be instantiated. Shape s = new Circle(2) compiles if Circle is a concrete subclass. new Shape[10] compiles: it creates an array of ten null references, not Shape objects.
A subclass of MediaItem doesn't implement summary. What are your two options to make it compile?
Implement summary in the subclass, or declare the subclass abstract as well, leaving the implementation to its subclasses.
Why not just give MediaItem.summary() a body that returns ""?
Then subclasses could forget to override it and silently return an empty description. Making it abstract forces every concrete subclass to provide a real implementation, which the compiler checks.
Can a method be both abstract and final? Abstract and static?
No to both. An abstract method must be overridden to be useful, but a final method can't be overridden, and static methods aren't overridden at all. The compiler reports an illegal combination of modifiers.
Previous: Java Varargs: Methods with a Variable Number of Arguments
Next: Java Enum Classes: Enumerated Types with Fields and Methods
Related reading

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.