This blog post is in response to a student's question about Java abstract classes and interfaces.
- What is the difference in abstract classes and interfaces?
- 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.
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:
- https://www.geeksforgeeks.org/difference-between-abstract-class-and-interface-in-java/
- Video on interface and inheritance: https://www.youtube.com/watch?v=mSjAJn4hUqg&feature=youtu.be
- Quick informational Abstract classes. https://www.w3schools.com/java/java_abstract.asp
- Quick informational on Interfaces. https://www.w3schools.com/java/java_interface.asp
Top comments (0)