Golang学习 接口、多态性

多态特性所具备的基本要素:父类(接口)、子类(实现了父类的接口)、父类的变量(指针)引用子类的具体变量数据。

对外暴露的是父类(接口),最终实现功能的是子类。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值