php的抽象类

mac2022-06-30  43

php的抽象类


 

//定义一个老虎类 abstract class Tiger{ public abstract function climb(); } //定义一个孟加拉虎类 class MTiger extends Tiger{ public function climb(){ echo '孟加拉虎,会爬树'; } } //定义一个西伯利亚虎类 class XTiger extends Tiger{ public function climb(){ echo '西伯利亚虎,不会爬树'; } } //定义一个猫类 class Cat{ public function climb(){ echo '猫,会爬树'; } } //定义一个动物类 class Client{ static function call(XTiger $animal){ $animal->climb(); } static function call2(Tiger $animal){ $animal->climb(); } static function call3($animal){ $animal->climb(); } } Client::call(new XTiger());//正确 Client::call(new MTiger());//不正确 //Fatal error: //Uncaught TypeError: Argument 1 passed to Client::call() must be an instance of XTiger, instance of MTiger given, called in ... Client::call(new Cat());//不正确 //Uncaught TypeError: Argument 1 passed to Client::call() must be an instance of XTiger, instance of MTiger given, called in ... echo '<hr>'; Client::call2(new XTiger());//正确 Client::call2(new MTiger());//正确 Client::call2(new Cat());//不正确 //Fatal error: Uncaught TypeError: Argument 1 passed to Client::call2() must be an instance of Tiger, instance of Cat given, called in echo '<hr>'; Client::call3(new XTiger());//正确 Client::call3(new MTiger());//正确 Client::call3(new Cat());//正确

总结:

1、定义为抽象的类不能被实例化;2、如果一个类里面至少有一个方法是被声明为抽象的, 那么这个类就必须被声明为抽象的。3、被定义为抽象的方法只是声明了其调用方式(参数),不能定义其具体的 功能实现。4、继承一个抽象类的时候,子类必须定义父类中的所有抽象方法, 这些方法的访问控制必须和父类中一样(或者更为宽松)

5、当参数指定类型时,必须符合类型,示例中:

   Client类的call方法,参数指定为 XTiger 时,只能传递Xtiger对象;

  Client类的call2方法,参数指定为 Tiger 时,只能传递Tiger的子类的对象;

  Client类的call3方法,参数不指定类型时,可以传递任何参数。

6、抽象类的关键字,abstract。


 

转载于:https://www.cnblogs.com/gyfluck/p/9674400.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)