We know that an interface is defined by the
interface keyword and all methods are abstract. All methods declared in an interface must be public; this is simply the nature of an interface.
Here is an example:
In an interface, the method body is not defined, just the name and the parameters. If we do not use an interface, what problems will be encounter? Why should we use
You’ll get answers to these questions in this article. Please see the code below:
In the above example, I do not use
interface. I write to the log using the
But, if I want to write a log using
LogToDatabase, I have to change the hard-coded class reference in the above code on line number 23.
That line code is:
public function __construct(LogToFile $logger)
This code will be:
public function __construct(LogToDatabase $logger)
In a large project, if I have multiple classes and I need to change them, I have to change all the classes manually.
But, if we use an interface, this problem is solved; we will not need to change code manually.
Now, see the following code and try to understand what happens if I use
Now, if I change from
LogToFile, I do not have to change the constructor method manually. In the constructor method, I have injected an
interface; not an arbitrary class.
If you have multiple classes and swap from one class to another class, you will get the same result without changing any class references.
In the above example, I write the log using
LogToDatabase and now I want to write the log using
I can call it like this:
$controller = new UsersController(new LogToFile);
I get results without changing other classes because
interface handle this swapping issue.
An abstract class is a class that is only partially implemented by the programmer. It may contain at least one
abstract method, which is a method without any actual code in it — just the name and the parameters, and that it has been marked as “abstract”.
An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class.
Here is an example:
Now, the question is: “How do we know that a method will be needed and that it must be implemented?” I will try to explain this here.
Please see the
Now, we look at the
In the two classes above, the three methods
addMilk() are the same.
So, we should remove duplicate code. We can do that like this:
I make an
abstract class and name it
Here, I define
addMilk(), and make an abstract method named
Now, if I make the
Tea class extend the
Template class, I will get the three defined methods and I have to define the
addPrimaryToppings() method. The
Coffee class will as well, in a similar way.
And if you’d like to practice and get code about
abstract classes, please check out my GitHub (stars always appreciated) repository.
Thanks for reading.