"""
package main
import (
"fmt"
)
// 指针
// 父类
type AnimalIF interface {
Sleep() // 睡觉
GetColor() string // 颜色
GetType() string // 种类
}
// 子类
type Cat struct {
color string // 颜色
}
func (this *Cat)Sleep() {
fmt.Println("Cat is sleeping...")
}
func (this *Cat)GetColor() string {
return this.color
}
func (this *Cat)GetType() string {
return "Cat"
}
// 子类
type Dog struct {
color string
}
func (this *Dog)Sleep() {
fmt.Println("Dog is sleeping...")
}
func (this *Dog)GetColor() string {
return this.color
}
func (this *Dog)GetType() string {
return "Dog"
}
func showAnimal(animal AnimalIF) {
animal.Sleep() //多态
fmt.Println("color =",animal.GetColor())
fmt.Println("kind =",animal.GetType())
}
func main() {
//var animal AnimalIF //接口数据类型
//animal = &Cat{"Green"}
//
//animal.Sleep()
//animal.GetType()
//animal.GetColor()
//
//animal = &Dog{"Yellow"}
//
//animal.Sleep()
//animal.GetType()
//animal.GetColor()
cat := Cat{"Green"}
//dog := Dog{"Yellow"}
showAnimal(&cat)
//showAnimal(&Dog)
dog := Dog{"Yellow"}
showAnimal(&dog)
}
+++++++++++++++++++++ 总结 ++++++++++++++++++++++++
/**
多态 :有父类 ; 有子类 实现了所有父类的方法 ;有指向父类的指针
*/
"""
网友评论