Abstract Class VS Interface
The two seems really similar. Lots of website talks about it, and most fail to explain the underlying differences. Because, an abstract class with all class abstract, no fields, it is just like an interface.
The most important difference lies in the relationship between abstract class and the concrete classes that inherit from it, and between the interface and the classes that implements it.
Abstract class and concrete classes have a close relationship. For example, an abstract class is Figure
and the concrete classes are Square
and Circle
. Square and Circle are closely related to a Figure. However, Square and Circle can implement
PrintToScreen. PrintToScreen
is an interface. It lists the required algorithm to print to screen. With PrintToScreen, Square and Circle can have its own way of printing to screen. But also, classes like Windows
, Browsers
, CatPictures
, etc, they all can implement PrintToScreen
.
Figure is very related to Square and Circle, so it works best with an Abstract Class relationship.
PrintToScreen and the other classes are not related, but the other classes would like to follow the same algorithm to print to screen. So an interface relationship works here.
###Other Differences and Similarities###
Abstract Class | Interface |
---|---|
inherited by subclasses | implemented by classes |
contains abstract, public, private, protected, etc. | contains abstract and public only |
can implement some methods | cannot implement any methods |
can contain fields | cannot contain fields |
cannot instantiate directly | cannot instantiate directly |
class can only inherit one abstract class | class can implement multiple interfaces |
So if an abstract class has only public/abstract methods and no fields, it would be the same as an interface, EXCEPT that classes can implement any interfaces, but only inherit one class (abstract or not), and the relationship between them I talked about earlier.