1. What is Abstract class?
- The abstract class is simply considered a superclass for all classes with the same nature.
- Each child class can only inherit directly from one parent class using the extends keyword.
- Objects of abstract class cannot be instantiated.
- Methods in abstract class can be abstract methods or not. If the method is abstract, it is only allowed to declare the name but not write the content.
- Subclasses inheriting from abstract must override abstract methods in them.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | <?php // Parent class abstract class Car { public $name; public function __construct($name) { $this->name = $name; } abstract public function intro() : string; } // Child classes class Audi extends Car { public function intro() : string { return "Choose German quality! I'm an $this->name!"; } } class Volvo extends Car { public function intro() : string { return "Proud to be Swedish! I'm a $this->name!"; } } // Create objects from the child classes $audi = new audi("Audi"); echo $audi->intro(); echo "<br>"; $volvo = new volvo("Volvo"); echo $volvo->intro(); echo "<br>"; ?> |
2. What is an interface?
- Interface is not a class, but a blueprint for classes that have the same way of operation.
- Can not define properties, initialize the object, but only declare methods in the interface.
- Methods can only declare names but not write content in them.
- The methods of the interface must be public.
- If the class inherits from the interface, it must override all the methods in it.
- A class can inherit from many different interfaces.
For example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php interface Animal { public function makeSound(); } class Cat implements Animal { public function makeSound() { echo "Meow"; } } $animal = new Cat(); $animal->makeSound(); ?> |
Difference between interface and abstract class
- All methods in an interface are always (understood) as abstract.
- Methods in abstract class are abstract or not abstract.
- It is possible to implements many interfaces but cannot extend many classes directly.
- The methods in the interface must always be public, other than the abstract class can be public, private or protected.
Similarity between interface and abstract class
- Cannot create a variable of type interface or abstract class.
- If the method is abstract, it must be declared in the subclass.
- Both the interface and the abstract class are inheritance.
When to use the interface, when to use abstract class
- When a group of objects have the same nature inheriting from a class, use abstract class.
- When a group of objects do not have the same nature but act the same, use the interface.