What is the key difference between Interface and Abstract Class
The key difference lies in purpose and approach of their usage.
1. Key Differences Between Interface and Abstract Class
Feature | Interface | Abstract Class |
---|---|---|
Method Implementation | Only method signatures (no implementation) | Can have both abstract and concrete (implemented) methods |
Properties | Cannot have properties (variables) | Can have properties (variables) |
Constructor | Cannot have a constructor | Can have a constructor |
Multiple Inheritance | A class can implement multiple interfaces | A class can extend only one abstract class |
Access Modifiers | All methods must be public | Methods can have public , protected , or private visibility |
Use Case | Defines a contract that multiple classes must follow | Provides a base class with some common functionality |
Interface
An interface in php is a contract, set of rules that classes need to follow. Interface define set of method that classes must impliment. Interface only contain signature/declaration of the methods. Classes that implement that interface implement those method according to the need.
When to use Interfaces
We use Interface when we want to define contract that multiple classes must follow without enforcing them to specific implementation.
Use Cases:
1. When multiple unrelated classes need to implement same method according to their requirement.
2. This provide consistency across multiple classes.
3. This also come in use when you want to implement dependency injection
Abstract Class
Abstract class in php is a class that cannot be instantiated and it is meant to be extended by other classes. Abstract class have at least one abstract method. It provide its declaration but implemented by sub classes. Abstract class can have both abstract method(without implementation) and regular method(with implementation).
When to use abstract class
We use abstract class when we want partial implementation of functionality that multiple related classes should inherit.
Use Cases:
1) Creating base class with shared common logic. (The properties and method can be use in child classes)
2) Child classes needs to share properties or default behavior.
3) When you want to enforce child classes to implement specific method.
Final Thoughts
Use an interface when you want to define behavior but not enforce how it is implemented.
Comments
Post a Comment