验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

在Hack中如何实现类的继承和多态

阅读:460 来源:乙速云 作者:代码code

在Hack中如何实现类的继承和多态

在Hack中,可以通过使用接口和抽象类来实现类的继承和多态。

  1. 继承:在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方法。

  1. 多态:在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函数,实现了多态的效果。

分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>