<?php
//抽象类
abstract class shape{
abstract function getarea(); //计算面积的方法
}
abstract class polygon extends shape{
abstract function getnumberofsides(); //计算边数的方法
}
//三角形类
class tirangle extends polygon{
public $base;
public $height;
public function getarea(){
return (($this->base*$this->height)/2);
}
public function getnumberofsides(){
return 3;
}
}
//长方形类
class rectangle extends polygon{
public $width;
public $height;
public function getarea(){
return ($this->width*$this->height);
}
public function getnumberofsides(){
return 4;
}
}
$t=new tirangle();
$t->base=10;
$t->height=10;
echo $t->getarea()."<br/>";
echo $t->getnumberofsides()."<br/>";$r=new rectangle();
$r->width=10;
$r->height=10;
echo $r->getarea()."<br/>";
echo $r->getnumberofsides()."<br/>";
?>
上面这个程序是看教科书打的,意思也明白了,程序运行也对。但就是不明白实际的意义。三角和长方的类我可以单独写出来,不比继承抽象类,代码也更简化,那抽象类有什么用了?
//抽象类
abstract class shape{
abstract function getarea(); //计算面积的方法
}
abstract class polygon extends shape{
abstract function getnumberofsides(); //计算边数的方法
}
//三角形类
class tirangle extends polygon{
public $base;
public $height;
public function getarea(){
return (($this->base*$this->height)/2);
}
public function getnumberofsides(){
return 3;
}
}
//长方形类
class rectangle extends polygon{
public $width;
public $height;
public function getarea(){
return ($this->width*$this->height);
}
public function getnumberofsides(){
return 4;
}
}
$t=new tirangle();
$t->base=10;
$t->height=10;
echo $t->getarea()."<br/>";
echo $t->getnumberofsides()."<br/>";$r=new rectangle();
$r->width=10;
$r->height=10;
echo $r->getarea()."<br/>";
echo $r->getnumberofsides()."<br/>";
?>
上面这个程序是看教科书打的,意思也明白了,程序运行也对。但就是不明白实际的意义。三角和长方的类我可以单独写出来,不比继承抽象类,代码也更简化,那抽象类有什么用了?
类 ->动物
方法->走 (抽象方法)有个类 猫头鹰 继承 动物
实现方法 ->走 (自己的走法 飞)有个类 鱼 继承 动物
实现方法 ->走 (自己的走法 游)