GoLang中的方法继承和方法重写(Demo)
父类型
package test
import "fmt"
type Person struct {
}
func (p Person) PrintStr() {
fmt.Println("Parent Print")
}
func (p Person) PrintStr2() {
fmt.Println("Parent Print 2")
}
子类型
package test
import "fmt"
type Children struct {
Person
}
/**
重写PrintStr
*/
func (c Children) PrintStr() {
fmt.Println("Children Print")
}
主函数内测试
package main
/*
* @Author: zhaojl
* @Date: 2022-06-11 15:58:48
* @LastEditTime: 2022-06-12 22:47:57
* @LastEditors: zhaojl
* @Description:
* @FilePath: \test1\main.go
*/
import "test1/test"
func main() {
children := test.Children{}
//子类型调用父类型方法
children.PrintStr2()
//子类型调用重写的方法
children.PrintStr()
}