Interfaces can be thought of as a ‘higher’ level of abstraction than Abstract Class. They generally define the behaviour of an class through Constants or abstract methods. Classes that implement an interface should follow the behaviour defined by that interface.
Just like Inheritance enforces an “is a” relationship between classes, interfaces enforce a “can do” relationship between itself and any classes that implement it.
In Java
Interfaces are, by convention, defined with identifiers ending with <...-able>
, such as <Drivable>
, <Writeable>
, etc.
Alternatively, interfaces are denoted with a capital I before the name, as such:
<ISubscriber>, <IDamager>, etc.
In Java, a class can implement multiple interfaces
The interface
keyword is used to define a class as an interface, and when done correctly, Java implicitly:
- Converts all methods to abstract methods
- Converts all attributes to static constants
- Makes all methods and attributes public
Just as extends
means a class is a subclass of a parent class, Java uses the keyword implements
to define when a class implements an interface.
Interfaces add a strict behaviour to classes that implement them:
- Any concrete (non-abstract) class that
implements
an interface must implement all the methods defined in the interface. - Else, the class must be defined as abstract