继承
继承是一种面向对象编程的概念,它允许我们创建一个新的类,该类从现有的类中继承属性和方法。继承可以减少代码重复,并允许我们构建更复杂的对象层次结构。
class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class Dog extends Animal {
public function bark() {
echo "Woof!";
}
}
$dog = new Dog("Fido");
echo $dog->getName(); // 输出 "Fido"
$dog->bark(); // 输出 "Woof!"
在上面的例子中,我们定义了一个名为Animal的类,它有一个名为name的属性和一个名为getName()的方法。我们还定义了一个名为Dog的类,它从Animal类继承了name属性和getName()方法,并添加了一个名为bark()的方法。
多态性
多态性是面向对象编程的一个概念,它允许我们使用相同的方法来处理不同类型的对象。多态性可以提高代码的灵活性和可扩展性。
class Shape {
protected $color;
public function __construct($color) {
$this->color = $color;
}
public function getColor() {
return $this->color;
}
public function getArea() {
// 抽象方法
}
}
class Rectangle extends Shape {
protected $width;
protected $height;
public function __construct($color, $width, $height) {
parent::__construct($color);
$this->width = $width;
$this->height = $height;
}
public function getArea() {
return $this->width * $this->height;
}
}
class Circle extends Shape {
protected $radius;
public function __construct($color, $radius) {
parent::__construct($color);
$this->radius = $radius;
}
public function getArea() {
return pi() * pow($this->radius, 2);
}
}
$shapes = array(
new Rectangle("red", 5, 10),
new Circle("blue", 3)
);
foreach
文章介绍了面向对象编程中的两个关键概念:继承和多态性。继承允许子类从父类获取属性和方法,减少代码重复,构建复杂的对象结构。多态性则提高了代码的灵活性和可扩展性,允许使用相同的方法处理不同类型的对象。文中通过Animal和Dog类以及Shape、Rectangle和Circle类的例子展示了这两个概念的应用。
783

被折叠的 条评论
为什么被折叠?



