Java Abstract Classes vs. Interface
Published in
2 min readSep 3, 2018
What are the differences between the two? Now that Java 8 enables default methods in interfaces, do you even need abstract classes at all?
Lets go over the attributes of an Abstract Class:
- they may or may not include abstract methods
- if a class includes abstract methods, then the class itself must be declared abstract
Now, similarities between Abstract Class and Interface:
- can contain a mix of methods with or without implementation
- both cannot be instantiated
Differences between the two:
Abstract Class:
- can declare fields that are not static and final
- can define public, protected, and private methods
- can only extend one class ( for any class )
Interface:
- all fields are automatically static and final
- methods are automatically public
- methods are implicitly abstract unless declared otherwise
- can implement many interfaces
And when you should consider using each of them:
Abstract Class:
- want to share code among closely related classes
- expect a class that extends an abstract class to have many common fields and methods, or require access modifiers other than public
- want to declare non-static and non-final fields. Also enables you to define methods that can access and modify the state of object to which they belong
Interface:
- expect unrelated classes to implement the interface (e.g interface Comparable and Cloneable are implemented by many unrelated classes)
- want to specify behavior but is not concern about who implements it
- want to take advantage of multiple inheritance
Note that in code, “extends” comes before “implements” or else you will get a compiler error, e.g class A extends B implements C
.