Conteúdo do Curso
Java OOP
Java OOP
Abstract Class vs Interface
Which one to choose?
From the previous chapters, you might have noticed that abstract classes
and interfaces
are quite similar. However, there are differences between them. To cut to the chase, it can be said that in practice, interfaces are often preferred over abstract classes. But let's understand why this is the case.
What's the difference?
To begin with, we need to understand the differences between an abstract class and an interface. Let's go through the list:
- Syntax:
abstract class
when declaring an abstract class andinterface
when declaring an interface; - Inheritance keyword:
extends
for inheriting an abstract class, andimplements
for inheriting an interface; - Names for subclasses: A subclass of an
abstract class
is referred to as a subclass or inheriting class, while a subclass of aninterface
is called a class - implementation; - Number of inheritances: You can inherit from only one abstract class, while you can inherit from multiple interfaces;
- An
abstract class
can have both implemented and abstract methods. Starting from Java 8, interfaces can also havedefault
methods, which we will discuss later in this section; - Methods in an abstract class can have any access modifier, whereas, in interfaces, only the
public
access modifier is allowed.
Note
We can also simultaneously inherit from an abstract class and implement an interface. First, we use the keyword
extends
, and then we useimplements
. The syntax looks like this:class ClassName extends AbstractClass implements Interface {
In simple terms, think of an abstract class as a class that provides some functionality and enforces certain rules but leaves some parts for its subclasses to complete. An interface, on the other hand, is like a checklist that a class needs to fulfill, specifying what methods it must have, without providing any actual code.
Obrigado pelo seu feedback!