在Hack中如何实现类的继承和多态
在Hack中,可以通过使用接口和抽象类来实现类的继承和多态。
- 继承:在Hack中,可以使用extends关键字来实现类的继承。例如:
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方法。
- 多态:在Hack中,可以通过接口和抽象类实现多态。例如:
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函数,实现了多态的效果。