继承

112 字
1 分钟
继承

继承#

父类Human

type Human struct {
name string
sex string
}
func (this *Human) Eat() {
fmt.Println("Human.Eat()...")
}
func (this *Human) Walk() {
fmt.Println("Human.Walk()...")
}

子类SuperMan

// Human子类
type SuperMan struct {
Human // SuperMan继承Human
level int
}
// 重写父类方法Eat
func (this *SuperMan) Eat() {
fmt.Println("SuperMan.Eat()...")
}
// 子类特有方法
func (this *SuperMan) Fly() {
fmt.Println("SuperMan.Fly()...")
}
func main() {
h := Human{"zhangsan", "man"}
h.Eat()
h.Walk()
//s := SuperMan{Human{"zhangsan", "man"}, 100}
s := SuperMan{h, 100}
s.level = 999
s.Eat()
s.Fly()
s.Walk()
fmt.Println("superman:", s)
}
-----------------
Human.Eat()...
Human.Walk()...
Human.Walk()...
SuperMan.Eat()...
SuperMan.Fly()...
superman: {{zhangsan man} 999}

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

继承
https://shaio.top/posts/丫丫学语/golang/继承/
作者
沙海
发布于
2026-08-10
许可协议
CC BY-NC-SA 4.0

评论区

Profile Image of the Author
沙海
Hello, I'm Shai.
公告
欢迎来到我的博客!这是一则示例公告。
音乐
封面

音乐

暂未播放

0:00 0:00
暂无歌词
分类
标签
站点统计
文章
84
分类
15
标签
48
总字数
67,035
运行时长
0 天
最后活动
0 天前
站点信息
构建平台
GitHub Actions
博客版本
Firefly v6.12.2
文章许可
CC BY-NC-SA 4.0

文章目录