Inheritance and rewriting of method in Go language

    Method is also called method. Go language supports method inheritance and rewriting.

One, method inheritance

    The method can be inherited. If the anonymous field implements a method, the struct containing the anonymous field can also call the method in the anonymous structure.
    The case is as follows:
//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()

}

    The effect is as follows:


Figure (1) Subclass calls the method of the parent class

Two, method rewrite

    The subclass rewrites the method function of the parent class with the same name; when calling, the method of the subclass is called first, if the subclass does not exist, the method of the parent class is called.
    The case is as follows:
//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()

}

    The effect is as follows:


Figure (2) The subclass calls its own method

Guess you like

Origin blog.csdn.net/sanqima/article/details/108902711