I was wondering how you guys decide when to use abstract or interface class during the application development since they both provide similar functionalities with slightly difference. I appreciate any helps. Thanks.
In PHP you can use interfaces define common functionality that is provided my similar classes. Abstract classes are used to define base classes that provide common functionality. Despite interfaces and abstract classes are somewhat related, they are not the same.
The short answer: An abstract class allows you to create functionality that subclasses can implement or override. An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces.
Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can't be instantiated. But there are many differences between abstract class and interface that are given below. 1) Abstract class can have abstract and non-abstract methods.
A concrete example of an abstract class would be a class called Animal. You see many animals in real life, but there are only kinds of animals. That is, you never look at something purple and furry and say "that is an animal and there is no more specific way of defining it".
Use abstraction if you have default methods (with accompanying code) for inheritors. Use interfaces if you just need to make sure that classes inheriting from this parent should implement all methods defined. Word of caution: use abstract classes and interfaces only if you intend to enforce structure and organization (usually with a team). There's a performance overhead.
I use abstract classes when I want the inheriting classes to inherit some functionality, and interfaces when I want to set some minimum structural criteria for a group of classes.
One thing to remember is that any given class can "inherit" (technically implement) many interfaces but only one sub-class (be that abstract or not).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With