go_study/src/c12_extend/extension_test.go
2023-03-01 11:23:26 +08:00

69 lines
1.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package extension_test
import (
"fmt"
"testing"
)
// golang是可以实现继承的但是这种继承并不是严格意义上的继承
// golang并不支持继承特性因而也没有单继承,多继承,重写方法等复杂概念。
type Pet struct {
}
func (p *Pet) Speak() {
fmt.Println("...")
}
func (p *Pet) SpeakTo(host string) {
p.Speak()
fmt.Println(host)
}
// 有名继承
type Dog struct {
p *Pet
}
func (d *Dog) Speak() {
fmt.Println("汪汪汪!")
}
func TestDog(t *testing.T) {
dog := new(Dog)
dog.Speak()
// dog.SpeakTo("Zhang") Dog没有这个方法, 虽然Pet有但是此时Dog不是匿名继承 ,如果要要调用需要指定继承事指定的名称。
dog.p.Speak()
dog.p.SpeakTo("Li")
}
// 匿名继承
type People struct {
}
func (p *People) ShowA() {
fmt.Println("AAA")
}
func (p *People) ShowB() {
fmt.Println("BBB")
}
type Doctor struct {
People
}
func (p *Doctor) ShowA() {
fmt.Println("Doctor AAA")
}
func TestDoctor(t *testing.T) {
d := new(Doctor)
d.ShowA()
d.ShowB() // 因为Teacher没有ShowB()的方法此时又匿名继承了People所以会调到People实现的ShowB方法
d.People.ShowA()
d.People.ShowB()
}