DEV Community

Cover image for Difference in Java Abstract Classes vs Interfaces
JC Smiley
JC Smiley

Posted on

Difference in Java Abstract Classes vs Interfaces

This blog post is in response to a student's question about Java abstract classes and interfaces.

  1. What is the difference in abstract classes and interfaces?
  2. When do you use one over the other?

The difference

  • Each class will extend one abstract class. An example is a Housecat class extending one abstract Cat class.
  • Each class can have multiple interfaces. That same Housecat class may have an Animal, Mammal, and DomesticPet interfaces.
  • Abstract classes' methods can have implementation ( a body). Their job is to set the default methods for the subclasses. There are different types of methods that can be used including abstracts (no body), static, and default methods.
  • Interfaces can only have abstract methods (no body).

I'm going to show when to use each with several examples.

Example 1

Imagine you have classes Housecat, Tiger, Ant, and Human. You can have an Animal abstract class to add functionality and properties that is used by all subclasses. You can then have a Cat interface for the cat type classes and a Mammal interface for all classes except ant.

In this example, the Housecat extends the Cat abstract class, Cat interface, and Mammal interface.

picture of HouseCat java code

Example 2

Imagine you have a Ford Mustang car and a Chevy Tahoe truck. You can create a vehicle abstract class to extend both classes. You can create a Car and Truck interface to extend each class. The benefit of this is if you buy a Ford truck, you can extend the Truck interface to give it truck functionality.

Example 3

Imagine you are baking a cake. An interface lists just the ingredients for the cake. An Abstract class lists not only the ingredients, but the instructions and pictures on how to bake it.

Additional resources:

If you have better examples or a better explanation, please answer in the comments so we all can learn.

Top comments (0)