Chinaunix

标题: abstract抽象类 [打印本页]

作者: xmlamp    时间: 2010-01-20 13:41
标题: abstract抽象类
抽象类机制中总是要定义一个公共的基类,而将特定的细节保留给继承者来实现。
要充分发挥抽象类的特点,就必须牢记以下规则:
1.某个类只要包含至少一个抽象方法就必须被声明为抽象类。
2.声明为抽象的方法,在实现的时候必须包含相同的或者更低的访问级别。
3.不能使用new关键字创建抽象类的实例。
4.被声明为抽象的方法不能包含函数体。
5.如果将扩展的类也声明为抽象的,在扩展抽象类时,就可以不用实现所有的抽象方法。
在创建具有层次结构的对象时,这种做法是很有用的。
在类的声明中使用abstract修饰符就可以将某个类声明为抽象的。

abstract class Car{
     abstract function getMaximumSpeed();
}
由于这个类是抽象的,不能实例化,它本身起不到什么作用。要让这个类起作用并且获得一个实例,首先必须扩展它。
class FastCar extends Car{
     function getMaximumSpeed(){
           return 150;
     }
}
现在有了一个可以实例化的类FastCar。
class Street{
     protected $speedLimit;
     protected $cars;
     public function __construct($speedLimit = 200){
           $this->cars = array();
           $this->speedLimit = $speedLimit;
     }
     protected function isStreetLegal($car){
           if($car->getMaximumSpeed()speedLimit){
                  return ture;
           } else {
                  return false;
           }
     }
     public function addCar($car){
           if($this-isStreetLegal($car)){
                  echo 'The Car was allowed on the road.';
                  $this->cars[] = $car;
           } else {
                  echo 'The Car is too fast and was not allowed on the road.';
           }
     }
}

$street = new Street();
$street->addCar(new FastCar());

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/106588/showart_2154712.html




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2