当前位置:网站首页>方法的繼承和重寫

方法的繼承和重寫

2022-06-21 12:10:00 attempt_to_do

繼承

如果匿名字段實現了一個method,那麼包含這個匿名字段的struct也能調用該method。


package main
import "fmt"
type Human struct {
    
    name string
    age int
    phone string
}
type Student struct {
    
    Human //匿名字段
    school string
}
type Employee struct {
    
    Human //匿名字段
    company string
}
//在human上面定義了一個method
func (h *Human) SayHi() {
    
    fmt.Printf("Hi, I am %s you can call me on %s\n", 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()
}

重寫

如果Employee想要實現自己的SayHi,怎麼辦?簡單,和匿名字段沖突一樣的道理,我們可以在Employee上面定義一個method,重寫了匿名字段的方法。


package main
import "fmt"
type Human struct {
    
    name string
    age int
    phone string
}
type Student struct {
    
    Human //匿名字段
    school string
}
type Employee struct {
    
    Human //匿名字段
    company string
}
//Human定義method
func (h *Human) SayHi() {
    
    fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
}
//Employee的method重寫Human的method
func (e *Employee) SayHi() {
    
    fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", 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()
}
原网站

版权声明
本文为[attempt_to_do]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211159571695.html