天天看点

go接口封装继承多态

package main

import "fmt"

//实现封装、继承、多态

//创建接口
type Animal interface {
	msg()
}
//基类
type Pets struct {
	name string
	age int

}
//Dog类继承基类
type Dog struct {
	Pets
	color string
}
//Cat类继承基类
type Cat struct {
	Pets
	color string
}
//绑定接口的方法
func (d *Dog) msg() {
	fmt.Println("我是",d.name,"我今年",d.age,"岁了","我喜欢",d.color,"色")
}
func (c *Cat) msg() {
	fmt.Println("我是",c.name,"我今年",c.age,"岁了","我喜欢",c.color,"色")
}

//封装接口
func data(a Animal) {
	a.msg()
}
func main() {
	dog := Dog{Pets{"花花", 2}, "棕"}
	data(&dog)
	cat := Cat{Pets{"肉肉", 1}, "白"}
	data(&cat)
}
           
我是 花花 我今年 2 岁了 我喜欢 棕 色
我是 肉肉 我今年 1 岁了 我喜欢 白 色
           

继续阅读