I am trying to learn OOP in PHP, and I have some confusion about interfaces and abstract classes. They both contain no implementations, only definitions, and should be implemented through their sub-classes. What part of abstract classes clearly distinguishes them from interfaces? Also, due to their apparent similarities, based on what reasons should I decide to use one over the other?
Answer
It is possible to create abstract classes that contain concrete members, such as methods or properties. You still can't instantiate the abstract class directly, but any instantiated sub-classes can benefit from implemented members defined in the abstract class.
An interface, by comparison, never contains any implementation logic. It is down to each implementing class to provide the implementation of all members defined in the interface.
In terms of how I view the differences, a sub-class of an abstract is-a class of that type. e.g. Dog
is an Animal
. I see an interface as a does-a relationship. e.g. ICanDisplayImages
tells me that the implementing class can display images, but tells me nothing about what the class actually represents.
No comments:
Post a Comment