69 lines
1.2 KiB
Go
69 lines
1.2 KiB
Go
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()
|
||
}
|