栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

第004节:”继承”中的方法

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

第004节:”继承”中的方法

1.1 method继承

method是可以继承的,如果匿名字段实现了一个method,那么包含这个匿名字段的struct也能调用该method

package mainimport "fmt"type Human struct {    name  string    age   int    phone string}type Student struct {    Human  //匿名字段    school string}type Employee struct {    Human   //匿名字段    company string}func (h *Human) SayHi() {    fmt.Printf("Hi, I am %s you can call me on %sn", h.name, h.phone)}func main() {    mark := Student{Human{"Mark", 25, "222-222-YYYY"}, "MIT"}    sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"}    mark.SayHi()    sam.SayHi()}

运行结果:

Hi, I am Mark you can call me on 222-222-YYYYHi, I am Sam you can call me on 111-888-XXXX

1.2 method重写

package mainimport "fmt"type Human struct {    name  string    age   int    phone string}type Student struct {    Human  //匿名字段    school string}type Employee struct {    Human   //匿名字段    company string}//Human定义methodfunc (h *Human) SayHi() {    fmt.Printf("Hi, I am %s you can call me on %sn", h.name, h.phone)}//Employee的method重写Human的methodfunc (e *Employee) SayHi() {    fmt.Printf("Hi, I am %s, I work at %s. Call me on %sn", e.name,        e.company, e.phone) //Yes you can split into 2 lines here.}func main() {    mark := Student{Human{"Mark", 25, "222-222-YYYY"}, "MIT"}    sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"}    mark.SayHi()    sam.SayHi()}

运行结果:

Hi, I am Mark you can call me on 222-222-YYYYHi, I am Sam, I work at Golang Inc. Call me on 111-888-XXXX

方法是可以继承和重写的存在继承关系时,按照就近原则,进行调用

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/793605.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号