天天看點

Go語言中method方法的繼承與重寫

    method也叫方法,Go語言中支援method的繼承和重寫。

一、method繼承

    method是可以繼承的,如果匿名字段實作了⼀個method,那麼包含這個匿名字段的struct也能調⽤該匿名結構體中的method。

    案例如下:

//myMethod02.go

// myMehthodJicheng2 project main.go
package main

import (
	"fmt"
)

type Human struct {
	name, phone string
	age         int
}

type Student struct {
	Human
	school string
}

type Employee struct {
	Human
	company string
}

func (h *Human) SayHi() {
	fmt.Printf("大家好! 我是%s, 我%d歲, 我的電話是: %s\n",
		h.name, h.age, h.phone)
}

func main() {
	s1 := Student{Human{"Anne", "15012349875", 16}, "武鋼三中"}
	e1 := Employee{Human{"Sunny", "18045613416", 35}, "1000phone"}

	s1.SayHi()
	e1.SayHi()

}

           

    效果如下:

Go語言中method方法的繼承與重寫

圖(1) 子類調用父類的method

二、method重寫

    子類重寫父類的同名method函數;調用時,是先調用子類的method,如果子類沒有,才去調用父類的method。

    案例如下:

//myMethod2.go

// myMehthodJicheng2 project main.go
package main

import (
	"fmt"
)

type Human struct {
	name, phone string
	age         int
}

type Student struct {
	Human
	school string
}

type Employee struct {
	Human
	company string
}

func (h *Human) SayHi() {
	fmt.Printf("大家好! 我是%s, 我%d歲, 我的電話是: %s\n",
		h.name, h.age, h.phone)
}

func (s *Student) SayHi() {
	fmt.Printf("大家好! 我是%s, 我%d歲, 我在%s上學, 我的電話是: %s\n",
		s.name, s.age, s.school, s.phone)
}

func (e *Employee) SayHi() {
	fmt.Printf("大家好! 我是%s, 我%d歲, 我在%s工作, 我的電話是: %s\n",
		e.name, e.age, e.company, e.phone)
}

func main() {
	s1 := Student{Human{"Anne", "15012349875", 16}, "武鋼三中"}
	e1 := Employee{Human{"Sunny", "18045613416", 35}, "1000phone"}

	s1.SayHi()
	e1.SayHi()

}

           

    效果如下:

Go語言中method方法的繼承與重寫

圖(2) 子類調用自身的method