您好,登錄后才能下訂單哦!
在Hack中,可以通過(guò)使用接口和抽象類(lèi)來(lái)實(shí)現(xiàn)類(lèi)的繼承和多態(tài)。
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類(lèi)繼承自Animal類(lèi),并重寫(xiě)了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接口定義了一個(gè)calculateArea方法,Circle和Rectangle類(lèi)都實(shí)現(xiàn)了Shape接口,并實(shí)現(xiàn)了calculateArea方法。通過(guò)傳遞不同的Shape對(duì)象給printArea函數(shù),實(shí)現(xiàn)了多態(tài)的效果。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。