Limit Depth of Inheritance in Java

This post demonstrates how to limit the depth of Inheritance in your codes. We will use a class InheritanceUtils from Apache Commons Lang.

Inheritance is Evil

Yes, inheritance is evil. If we subclass too much in our code base, sooner or later things become too difficult to manage. Maintenance and code refactor nightmares ensue.

Good thing there is Composition! However, we’ll not discuss it here.

Example Codes

Okay, let’s say we have an existing API that uses too much inheritance. We modified a “common” generic class (or abstract class) to perform the inheritance depth check internally.

We have an interface for a translator. Other codes “uses” a translator by invoking the process  method.

We have a GenericTranslator  which is an abstract class. It defines the life-cycle of a translator.

Then, we have two implementations. We’ll use these classes to test our inheritance level check.

Direct Descendant to Generic Translator

Descendant of a Descendant


This outputs:

Eclipse Console output


Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert