Chinaunix首页 | 论坛 | 博客
  • 博客访问: 160948
  • 博文数量: 52
  • 博客积分: 2295
  • 博客等级: 大尉
  • 技术积分: 540
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-22 17:42
文章分类

全部博文(52)

文章存档

2013年(1)

2012年(11)

2011年(1)

2010年(31)

2009年(8)

我的朋友

分类:

2010-01-20 13:41:59

抽象类机制中总是要定义一个公共的基类,而将特定的细节保留给继承者来实现。
要充分发挥抽象类的特点,就必须牢记以下规则:
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()<$this->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());
阅读(601) | 评论(0) | 转发(0) |
0

上一篇:foreach,list()=each()

下一篇:interface

给主人留下些什么吧!~~