您好,登錄后才能下訂單哦!
在Hack中,可以通過使用接口和抽象類來實現類的繼承和多態。
class Animal {
public function speak(): void {
echo "Animal speaks";
}
}
class Dog extends Animal {
public function speak(): void {
echo "Dog barks";
}
}
$dog = new Dog();
$dog->speak(); // 輸出:Dog barks
在上面的例子中,Dog類繼承自Animal類,并重寫了speak方法。
interface Shape {
public function calculateArea(): float;
}
class Circle implements Shape {
private float $radius;
public function __construct(float $radius) {
$this->radius = $radius;
}
public function calculateArea(): float {
return 3.14 * $this->radius * $this->radius;
}
}
class Rectangle implements Shape {
private float $length;
private float $width;
public function __construct(float $length, float $width) {
$this->length = $length;
$this->width = $width;
}
public function calculateArea(): float {
return $this->length * $this->width;
}
}
function printArea(Shape $shape): void {
echo "Area: " . $shape->calculateArea() . "\n";
}
$circle = new Circle(5.0);
$rectangle = new Rectangle(4.0, 6.0);
printArea($circle); // 輸出:Area: 78.5
printArea($rectangle); // 輸出:Area: 24
在上面的例子中,Shape接口定義了一個calculateArea方法,Circle和Rectangle類都實現了Shape接口,并實現了calculateArea方法。通過傳遞不同的Shape對象給printArea函數,實現了多態的效果。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。