Search⌘ K
AI Features

Abstract Classes

Explore how to use abstract classes in Java to create class hierarchies that prevent instantiation of incomplete objects. Understand defining abstract methods, mixing concrete and abstract implementations, using constructors, and leveraging polymorphism for flexible, safe design in object-oriented programming.

We built class hierarchies where every class could be instantiated. However, in the real world, some concepts are too general to exist as standalone objects. Consider a “Payment.” You can make a credit card payment or a bank transfer, but you cannot simply make a “generic payment” without knowing the specific method.

In Java, we use abstract classes to represent these high-level concepts. They allow us to define a strict template for subclasses while preventing code from creating incomplete objects.

The need for abstraction

When we design a class hierarchy, the superclass often acts as a category rather than a specific entity. If we define a class named Shape, we intend for it to be a parent for Circle or Rectangle.

If Shape is a normal (concrete) class, nothing stops us from writing new Shape(). This creates a meaningless object that doesn't represent any actual shape. We need a way to tell the compiler: This class is just a blueprint for other classes. Do not allow anyone to create a direct instance of it.

Defining an abstract class

We declare a class as abstract using the abstract keyword. This signals the compiler ...