Interfaces – the next level of abstraction

737 0

Interfaces resemble abstract classes in that they include abstract methods that the programmer must define in the classes that inherit from the interface. In this way, interfaces contribute to code organization because they commit the child classes to the methods that they should implement. The use of interfaces become very helpful when we work in a team of programmers and want to ensure that all the programmers write the methods that they should work on, or even in the case of a single programmer that wants to commit himself to write certain methods in the child classes.

An interface commits its child classes to abstract methods that they should implement.

How to declare and implement an interface?
We declare an interface with the interface keyword and, the class that inherits from an interface with the implements keyword. Let’s see the general case:

In the simple example given below, we will create an interface for the classes that handle cars, which commits all its child classes to setModel() and getModel() methods.

Interfaces, like abstract classes, include abstract methods and constants. However, unlike abstract classes, interfaces can have only public methods, and cannot have variables.
The classes that implement the interfaces must define all the methods that they inherit from the interfaces, including all the parameters. So, in our concrete class with the name of miniCar, we add the code to all the abstract methods.

Can we implement more than one interface in the same class?
We can implement a number of interfaces in the same class.
We can implement a number of interfaces in the same class, and so circumvent the law that prohibits the inheritance from more than one parent class. In order to demonstrate multiple inheritance from different interfaces, we create another interface, Vehicle, that commits the classes that implement it to a boolean $hasWheels property.

Now, our child class can implement the two interfaces.

What are the differences between abstract classes and interfaces?

We saw that abstract classes and interfaces are similar in that they provide abstract methods that can be implemented only in the child classes. However, they still have the following differences:
• Interfaces can include abstract methods and constants, but cannot contain concrete methods and variables.
• All the methods in the interface must be in the public visibility scope.
• A class can implement more than one interface, while it can inherit from only one abstract class.

Let’s summarize these differences in the following table:
interfaces Abstract classes
the code abstract methods  & constant abstract methods   -constants -concrete methods -concrete variables
access modifiers -public -public -protected -private etc.
number of parents The same class can implement more than 1 interface The child class can inherit only from 1 abstract class



In this article

Join the Conversation