Home  >  Article  >  php教程  >  看看老外是如何理解抽象类的

看看老外是如何理解抽象类的

WBOY
WBOYOriginal
2016-06-07 17:23:531154browse

           下面是我翻译的关于帮助理解抽象类的例子。

           这是一个例子帮助我们理解抽象类。在我看来这是一个非常简单的方法。让我们一起来看看下面的代码:

<?php     
 class Fruit {     
    private $color;     
              
    public function eat() {     
        //chew     
    }     
              
    public function setColor($c) {     
        $this->color = $c;     
    }     
}     
          
class Apple extends Fruit {     
    public function eat() {     
        //chew until core     
    }     
}     
          
class Orange extends Fruit {     
    public function eat() {     
        //peel     
        //chew     
    }     
}     
?>

           现在我给一个苹果你吃

<?php     
  $apple = new Apple();     
  $apple->eat();     
?>

           感觉怎么样?它尝起来就像一个苹果。现在我给一个水果你吃。

           

<?php     
  $fruit = new Fruit();     
  $fruit->eat();     
?>

           吃水果???你能看出它是什么颜色,尝出是什么味道吗?感觉是不是怪怪的呢?所以你不能这样子做。

           现在让我们来看一下水果的正确吃法吧。

<?php     
  abstract class Fruit {     
    private $color;     
              
    abstract public function eat()     
              
    public function setColor($c) {     
        $this->color = $c;     
    }     
}     
?>

           现在想想,数据库和数据库扩展。此外,一个音符。一个抽象类,就像一个接口,你可以定义一个抽象类中的方法,而它们都是抽象接口。

           

          

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn