Kas saaksite rääkida päriluse põhimõtetest objektorienteeritud programmeerimises?
sobes.tech AI
Vastus AI-lt
Inheritance allows creating a new class (child or derived) based on an existing class (parent, base, or super class). The derived class inherits properties (attributes) and methods from the parent class, and can also add its own or override inherited ones.
Main concepts:
- Extending functionality: By inheriting from the parent class, the derived class gains the basic functionality and can extend it by adding new methods or properties.
- Overriding methods: The derived 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 allows avoiding code duplication, as the common logic is defined in the parent class.
- "Is-a" relationship: Inheritance models the "is a" relationship (is-a). 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 from only one class (single inheritance), but can implement multiple interfaces.
Access to parent class properties and methods from the child class is possible using the parent:: keyword:
<?php
class ParentClass {
protected $value = "parent value";
public function showValue() {
echo $this->value . "\n";
}
}
class ChildClass extends ParentClass {
// Override 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
?>
Access modifiers:
public: accessible everywhere.protected: accessible within the class and inheriting classes.private: accessible only within the class.
Methods can be declared as final, which prevents their override in derived classes. Classes can also be final, which prevents inheritance. They can also be abstract, which requires their implementation in derived classes.