Sobes.tech
Junior

Can you tell about the principles of inheritance in object-oriented programming?

sobes.tech AI

Answer from AI

Inheritance allows creating a new class (child or derived) based on an existing class (parent, base, or super class). The child class inherits properties (attributes) and methods of the parent class, and can also add its own or override inherited ones.

Main concepts:

  • Extending functionality: By inheriting from the parent class, the child class gains basic functionality and can extend it by adding new methods or properties.
  • Overriding methods: The child class can change the behavior of a method inherited from the parent class by creating a method with the same name (polymorphism).
  • Code reuse: It helps avoid code duplication, as common logic is defined in the parent class.
  • "Is-a" relationship: Inheritance models the "is-a" relationship. For example, "A cat is an animal".
<?php

class Animal {
    protected $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function speak() {
        echo "Unknown sound\n";
    }
}

class Dog extends Animal {
    public function speak() {
        echo "Woof!\n";
    }
}

class Cat extends Animal {
    public function speak() {
        echo "Meow!\n";
    }
}

$dog = new Dog("Bobby");
$dog->speak(); // Output: Woof!

$cat = new Cat("Murka");
$cat->speak(); // Output: Meow!

?>

In PHP, inheritance is implemented using the extends keyword. One class can inherit only from one class (single inheritance), but can implement multiple interfaces.

Access to the properties and methods of the parent class from the child is possible using the parent:: keyword.

<?php

class ParentClass {
    protected $value = "parent value";

    public function showValue() {
        echo $this->value . "\n";
    }
}

class ChildClass extends ParentClass {
    // Overriding property
    protected $value = "child value";

    public function showValues() {
        // Call parent class method
        parent::showValue();
        // Output child class value
        echo $this->value . "\n";
    }
}

$obj = new ChildClass();
$obj->showValues();
// Output:
// parent value
// child value

?>

Key access modifiers:

  • public: Accessible from anywhere.
  • protected: Accessible within the class and inheriting classes.
  • private: Accessible only within the class.

Methods can be declared final, which prohibits their overriding in child classes. Classes can also be final, which prevents inheritance. They can be abstract, which requires their implementation in child classes.

Can you tell about the principles of inheritance in… - sobes.tech