When to use abstract classes?

Richard has provided an example were an abstract class has advantages over non-abstract classes.

I would like to add a fact-table for choosing between an abstract class and an interface. The image can be found here.

enter image description here


You use them for classes which will never be created (so effectively don't exist), but you want to inherit from them for polymorphism reasons.


By using abstract classes we are able to make the class more generic.

For example: if class A is an abstract class and there are classes class B, class C and class D extending abstract class A then these sub-classes will inherit a method which is already declared in abstract class A thereby making the method more generic.


Abstract classes are useful when you need a class for the purpose of inheritance and polymorphism, but it makes no sense to instantiate the class itself, only its subclasses. They are commonly used when you want to define a template for a group of subclasses that share some common implementation code, but you also want to guarantee that the objects of the superclass cannot be created.

For instance, let's say you need to create Dog, Cat, Hamster and Fish objects. They possess similar properties like color, size, and number of legs as well as behavior so you create an Animal superclass. However, what color is an Animal? How many legs does an Animal object have? In this case, it doesn't make much sense to instantiate an object of type Animal but rather only its subclasses.

Abstract classes also have the added benefit in polymorphism–allowing you to use the (abstract) superclass's type as a method argument or a return type. If for example you had a PetOwner class with a train() method you can define it as taking in an object of type Animal e.g. train(Animal a) as opposed to creating a method for every subtype of Animal.