39. Abstract Classes and Methods
Abstract classes are partial blueprints. They cannot be instantiated directly, but they can be inherited by other classes. They enforce a structure that all child classes must follow.
Abstract Classes
- Defined using the
abstractkeyword. - Cannot be created with
new AbstractClass(). - Must contain at least one abstract method, but can also contain regular methods and properties.
Abstract Methods
- Methods declared with the
abstractkeyword. - They have no body (no
{}), only a signature. - Any concrete (non-abstract) child class that extends an abstract class must implement all abstract methods defined by the parent.
php
name = $name; } // Abstract method: forces children to define this behavior abstract public function makeSound(); // Regular method public function sleep() { echo "$this->name is sleeping."; } } // Concrete Class: MUST implement makeSound() class Dog extends Animal { public function makeSound() { return "$this->name says Woof!"; } } // Concrete Class: MUST implement makeSound() class Cat extends Animal { public function makeSound() { return "$this->name says Meow!"; } } $dog = new Dog("Sparky"); echo $dog->makeSound(); // Output: Sparky says Woof! ?>Purpose: To define a common interface and ensure that related classes share certain mandatory functionality.