Interfaces allow you to specify which methods a class must implement, without having to define how these methods are handled. They are used to create a common standard for different classes.
Think of an interface as a contract. If a class "signs" the contract (implements the interface), it promises to provide code for all the methods listed in that interface.
In this example, different animals must implement the makeSound() method, but each will do it in its own way:
While both force child classes to implement methods, they serve different purposes:
| Feature | Interface | Abstract Class |
|---|---|---|
| Multiple Inheritance | A class can implement many interfaces. | A class can extend only one class. |
| Functionality | Cannot contain any code or logic. | Can contain logic and regular methods. |
| Properties | Cannot have variables. | Can have variables. |
Interfaces enable Polymorphism. This means you can write code that works with any object that follows a specific interface, without caring about the actual class of the object. It makes your application highly decoupled and easy to extend.
Exportable could force classes like Invoice or UserReport to provide an exportToPDF() method.