一、Abstract Class簡介
Abstract Class是一種抽象類,它不能被實例化,只能被繼承。Abstract Class的主要作用是提供一個基類,定義一些抽象的方法,讓其子類去實現具體的邏輯,並通過這些抽象的方法來規範其子類。
Abstract Class可以看成是普通類和Interface的結合體,它既可以有普通類的方法、屬性和構造函數,也可以有Interface的抽象方法。
二、Abstract Class和普通類的區別
相對於普通類,Abstract Class有以下區別:
1、Abstract Class不能被實例化;
2、Abstract Class可以有抽象方法和普通方法;
3、Abstract Class中定義的抽象方法必須在其子類中實現;
4、一旦一個類繼承了Abstract Class,它必須實現該Abstract Class中所有的抽象方法才能被實例化。
三、Abstract Class和Interface的區別
相對於Interface,Abstract Class有以下區別:
1、Interface不能有普通方法,只能定義抽象方法;Abstract Class可以有抽象方法和普通方法;
2、一個類可以實現多個Interface,但只能繼承一個Abstract Class;
3、Interface中定義的抽象方法必須在實現類中全部實現,否則會報錯;Abstract Class中定義的抽象方法可以在子類中選擇性地實現;
4、Interface中不能有屬性,只能有常量;Abstract Class中可以有屬性和常量;
5、Interface不能有構造函數;Abstract Class可以有構造函數。
四、使用Abstract Class的注意事項
使用Abstract Class需要注意以下幾點:
1、Abstract Class不能被實例化,只能通過其子類來實例化;
2、Abstract Class中的抽象方法必須在其子類中全部實現;
3、Abstract Class中的普通方法可以在子類中選擇性地實現或覆蓋;
4、Abstract Class中可以有普通方法、常量和屬性,所以如果類中需要有一些共同的方法和屬性,且這些方法和屬性在所有的子類中都具有相同的作用和特性,那麼可以將這些方法和屬性寫在Abstract Class中,避免在所有的子類中重複書寫;
5、Abstract Class經常和模板方法模式一起使用,以實現代碼的重用。
五、代碼示例
abstract class Animal {
public $name;
public $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
abstract public function move();
}
class Dog extends Animal {
public function move() {
echo "$this->name is running!
";
}
}
class Cat extends Animal {
public function move() {
echo "$this->name is jumping!
";
}
}
$dog = new Dog('Tommy', 3);
$dog->move(); // Tommy is running!
$cat = new Cat('Kitty', 2);
$cat->move(); // Kitty is jumping!
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/184070.html
微信掃一掃
支付寶掃一掃