Interfaces and Implementing Interfaces

// Define the interface
interface Animal {
    public function makeSound();
}

// Implement the interface in a class
class Dog implements Animal {
    public function makeSound() {
        return "Woof! Woof!";
    }
}

class Cat implements Animal {
    public function makeSound() {
        return "Meow! Meow!";
    }
}

// Create instances of the classes and call the method
$dog = new Dog();
echo $dog->makeSound(); // Output: Woof! Woof!

$cat = new Cat();
echo $cat->makeSound(); // Output: Meow! Meow!

Explanation:

  • We define an interface Animal with a single method makeSound().
  • The Dog and Cat classes implement the Animal interface by providing an implementation for the makeSound() method.
  • Each class provides its own unique implementation of the makeSound() method according to the behavior of the animal.
  • When we create instances of the Dog and Cat classes and call the makeSound() method on them, we get the specific sound associated with each animal.

Interfaces allow for polymorphism, where different objects can be treated interchangeably based on the interface they implement. It promotes code reusability and flexibility in object-oriented designs.

Related Posts

Leave A Comment