博客列表 >继承、抽象类与接口、多态

继承、抽象类与接口、多态

ROC-Y
ROC-Y原创
2020年05月24日 01:25:31669浏览

抽象类继承实例

  1. <?php
  2. //定义抽象类,关键字abstract
  3. abstract class Shape {
  4. public $width ;
  5. public $heigth ;
  6. //调用length1方法,初始化变量
  7. function length1($width,$heigth){
  8. $this->width = $width;
  9. $this->heigth = $heigth;
  10. }
  11. abstract public function area();
  12. }
  13. class Rectangle extends Shape{
  14. //继承Shape,自动获得属性$width,$heigth,方法length1()
  15. //c重写area方法
  16. function area (){
  17. //返回面积
  18. return (($this->width * $this->heigth)/2);
  19. }
  20. }
  21. //创建rea实例
  22. $rec = new Rectangle;
  23. //给属性赋值
  24. $rec->length1(20,30);
  25. echo $rec->width."<br>";
  26. echo $rec->heigth."<br>";
  27. //输出rec面积
  28. echo $rec->area();

接口与多态

  1. <?php
  2. //定义接口,关键字interface
  3. interface Shape {
  4. function area();
  5. function perimeter();
  6. }
  7. //实现Shape,
  8. class Rectangle implements Shape{
  9. public $width;
  10. public $heigth;
  11. function length1($width,$heigth){
  12. $this->width = $width;
  13. $this->heigth = $heigth;
  14. }
  15. //重写area方法
  16. function area (){
  17. //返回面积
  18. echo "长方形面积:".($this->width * $this->heigth)/2 . "<br>";
  19. }
  20. //重写perimeter方法
  21. function perimeter(){
  22. //返回周长
  23. echo "长方形周长:".(($this->width + $this->heigth) * 2). "<br>";
  24. }
  25. }
  26. //实现Shape,
  27. class Circle implements Shape{
  28. public $radius ;
  29. //重写area方法
  30. function area (){
  31. //返回面积
  32. echo "圆的面积:".($this->radius) **2 * M_PI . "<br>";
  33. }
  34. //重写perimeter方法
  35. function perimeter(){
  36. //返回周长
  37. echo "圆的周长:". ($this->radius) *2 * M_PI . "<br>";
  38. }
  39. }
  40. //判断对象类型,如果是Shape,执行对应的方法,实现多态
  41. function change($obj){
  42. if($obj instanceof Shape){
  43. $obj->area();
  44. $obj->perimeter();
  45. }else{
  46. echo "传入的参数不是一个正确的Shape对象";
  47. }
  48. }
  49. //创建Rectangle实例
  50. $rec = new Rectangle;
  51. //给属性赋值
  52. $rec->length1(20,30);
  53. //创建Circle 对象
  54. $cir = new Circle;
  55. $cir->radius = 5 ;
  56. //调用change方法,实现多态
  57. change($rec);
  58. change($cir);

总结

  • 继承,可以将一些类的相似成员抽取出来到父类,子类通过继承得到这部分成员,实现代码简化和复用,子类重写父类方法,修饰符权限必须大于等于对应的父类方法。私有成员无法继承得到。
  • 抽象类,不能被实例化,抽象类可以有自己的属性和普通方法,可以对公有成员进行一些操作
  • 接口,PHP只支持单继承,但是可以多实现接口,是抽象类的一个特例,也是对继承的补充。
  • final 在特定的类前面,表示此类不能被继承,在方法前面,表示该方法不能被重写。
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议