Refactoring Extract Superclass


You have two classes with common fields and methods.


Create a shared superclass for them and move all the identical fields and methods to it.
Extract Superclass - Before
Extract Superclass - After

Why Refactor

One type of code duplication occurs when two classes perform similar tasks in the same way, or perform similar tasks in different ways. Objects offer a built-in mechanism for simplifying such situations via inheritance. But oftentimes this similarity remains unnoticed until classes are created, necessitating that an inheritance structure be created later.


  • Code deduplication. Common fields and methods now "live" in one place only.

When Not to Use

  • You can not apply this technique to classes that already have a superclass.

How to Refactor

  1. Create an abstract superclass.

  2. Use Pull Up Field, Pull Up Method, and Pull Up Constructor Body to move the common functionality to a superclass. Start with the fields, since in addition to the common fields you will need to move the fields that are used in the common methods.

  3. Look for places in the client code where use of subclasses can be replaced with your new class (such as in type declarations).

Tired of reading?

No wonder, there are 7 hours worth of the text on this website.

Try out something different. We've just launched the interactive learning course on refactoring. It has more content and much more fun than a boring text.

Learn more...

Live Example

First time here? No worries!

Everything is quite simple. This example is like video (but much cooler):

  1. After pressing the Play button, you will see floating messages, which will guide you through the example. You can proceed by clicking on them.
  2. You can fast-forward or return to previous steps by pressing arrow buttons on the left.
  3. Also, you can take a look at the code diff window, which will show what has changed in code during the example ()
  4. To check the code for errors, you can press "Compile and test" button ()