抽象类和接口都是面向对象编程中的重要概念,它们都具有一定的相似性,但也存在一些不同之处。
具体区别如下:
– 抽象类可以包含具体方法和抽象方法,而接口只能包含抽象方法和常量。
– 一个类只能继承一个抽象类,但可以实现多个接口。
– 抽象类可以包含属性,但接口不能包含属性。
– 抽象类的构造函数可以被子类调用,而接口没有构造函数。
以下是一个完整的示例:
// 抽象类
abstract class Animal {
// 抽象方法
abstract public function makeSound();
// 具体方法
public function eat() {
echo "The animal is eating.
";
}
}
class Dog extends Animal {
public function makeSound() {
echo "The dog is barking.
";
}
}
$dog = new Dog();
$dog->makeSound(); // Output: The dog is barking.
$dog->eat(); // Output: The animal is eating.
// 接口
interface Shape {
public function getArea();
}
class Rectangle implements Shape {
private $width;
private $height;
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
public function getArea() {
return $this->width * $this->height;
}
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function getArea() {
return pi() * pow($this->radius, 2);
}
}
$rectangle = new Rectangle(5, 10);
echo $rectangle->getArea(); // Output: 50
$circle = new Circle(5);
echo $circle->getArea(); // Output: 78.539816339745
注:代码中的注释已经解释了每个部分的作用。
正文完