---
title: "面向对象之多态"
author: "keshion"
date: "2013-02-01T17:49:12Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-02-01T17:49:12Z"
id: 1782873
url: "https://keshion.iteye.com/blog/1782873"
---

Java实现

```
//定义接口Animal  
interface Animal  
{  
    void Talk();  
}  
//实现接口Animal的Dog  
class Dog implements Animal  
{  
    public void Talk()  
    {          
        System.out.println("WongWong");  
    }   
}  
//实现接口Animal的类Cat  
class Cat implements Animal  
{  
    public void Talk()  
    {          
        System.out.println("Miao");  
    }   
}  
class Test  
{  
    public static void main(String[] args)  
    {   
        Animal  a;  
        a= new Dog();  
        a.Talk();   
        a = new Cat();   
        a.Talk();
    }   
}  
```

 

PHP实现

```
<?php
//定义接口Animal  
interface Animal  
{  
    public function Talk();  
}  
//实现接口Animal的Dog  
class Dog implements Animal  
{  
    public function Talk()  
    {          
        echo("WongWong");  
    }   
}  
//实现接口Animal的类Cat                                                                                                                     
class Cat implements Animal  
{  
    public function Talk()  
    {          
        echo("Miao");  
    }   
}  
$a = new Dog();  
$a->Talk();   
$a = new Cat();   
$a->Talk();
?>
```

 

在面向对象语言中，接口的多种不同的实现方式即为多态

设若干子类继承与父类，并且每个子类与父类、子类与子类之间有所差异

如果你把子类视为父类的话，那么这些子类就是父类的“多态”  
如果你把每个子类都是为独立的个体的话，那就无“多态”可言了

白猫会抓老鼠、黑猫会抓老鼠，因为它们都是猫  
多态表现在毛的颜色上