package main
import "fmt"
// go多态的实现
//1,有一个父类--- 接口
//2,有子类---实现接口中所有的方法
//3,父类对象指向子类的对象
//接口, 本质是个指针
type Animal interface {
Sleep()
GetColor() string
GetType() string
}
//具体的类
type Cat struct {
Color string
}
func (this *Cat) Sleep(){
fmt.Println("Cat is sleep")
}
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 sleep")
}
func (this *Dog) GetColor() string{
return this.Color
}
func (this *Dog) GetType() string{
return "dog"
}
func showAnimal(animal Animal){
animal.Sleep()
fmt.Println("color is: ", animal.GetColor())
fmt.Println("kind is: ", animal.GetType())
}
func main() {
var animal Animal //接口数据类型、父类对象
cat := Cat{"black"}
animal = &cat
animal.Sleep()
fmt.Println(animal.GetColor())
fmt.Println(animal.GetType())
dog := Dog{"yello"}
animal = &dog
animal.Sleep()
fmt.Println(animal.GetColor())
fmt.Println(animal.GetType())
showAnimal(&cat)
showAnimal(&dog)
}