多态特性所具备的基本要素:父类(接口)、子类(实现了父类的接口)、父类的变量(指针)引用子类的具体变量数据。
对外暴露的是父类(接口),最终实现功能的是子类。
package main
import "fmt"
// AnimalIF 本身是一个指针
type AnimalIF interface {
GetColor() string
GetType() string
Sleep()
}
type Dog struct {
color string
}
func (this *Dog) GetColor() string {
return this.color
}
func (this *Dog) GetType() string {
return "dog"
}
func (this *Dog) Sleep() {
fmt.Println(this.GetType(), "is sleeping")
}
//至此,Dog类已经实现了 Animal接口的所有方法。
type Cat struct {
color string
}
func (this *Cat) GetColor() string {
return this.color
}
func (this *Cat) GetType() string {
return "cat"
}
func (this *Cat) Sleep() {
fmt.Println(this.GetType(), "is sleeping")
}
func ShowAnimal(animal AnimalIF) {
animal.Sleep()
fmt.Println("Animal's color is", animal.GetColor())
fmt.Println("Animal's type is", animal.GetType())
}
func main() {
var animal AnimalIF //声明一个接口数据类型,他只是个指针
animal = &Dog{"brown"} //为这个接口具体化
animal.Sleep()
fmt.Println("Animal's color is", animal.GetColor())
fmt.Println("Animal's type is", animal.GetType())
fmt.Println("===================")
var animal2 AnimalIF = &Cat{"white"} //也可以声明的的时候直接实现接口
animal2.Sleep()
fmt.Println("Animal's color is", animal2.GetColor())
fmt.Println("Animal's type is", animal2.GetType())
fmt.Println("==========接下来将实现类的多态特性=========")
ShowAnimal(&Dog{"yellow"})
fmt.Println("===================")
ShowAnimal(&Cat{"blank and white"})
}
输出结果如下:
dog is sleeping
Animal's color is brown
Animal's type is dog
===================
cat is sleeping
Animal's color is white
Animal's type is cat
==========接下来将实现类的多态特性=========
dog is sleeping
Animal's color is yellow
Animal's type is dog
===================
cat is sleeping
Animal's color is blank and white
Animal's type is cat