Java
October 26, 2020

Theory: Abstract class

Sometimes you have a set of fields and methods that you need to reuse in all classes within a hierarchy. It is possible to put all the common members to a special base class and then declare subclasses which can access these members. At the same time, you do not need to create objects of the base class. To achieve it, you can use an abstract class as the base class in the hierarchy.

What is an abstract class?

An abstract class is a class declared with the keyword abstract. It represents an abstract concept that is used as a base class for subclasses.

Abstract classes have some special features:

  • it's impossible to create an instance of an abstract class;
  • an abstract class can contain abstract methods that must be implemented in non-abstract subclasses;
  • it can contain fields and non-abstract methods (including static);
  • an abstract class can extend another class, including abstract;
  • it can contain a constructor.

As you can see, an abstract class has two main differences from regular (concrete) classes: no instances and abstract methods.

Abstract methods are declared by adding the keyword abstract. They have a declaration (modifiers, a return type, and a signature) but don't have an implementation. Each concrete (non-abstract) subclass must implement these methods.

Note, static methods can't be abstract!