GO语言的继承和多态实现

继承

package extend

import (
	"fmt"
	"testing"
)

type Pet struct {
}

func (p *Pet) speak() {
	fmt.Print("...")
}

func (p *Pet) speakTo(name string) {
	p.speak()
	fmt.Print(name)
}

type Dog struct {
	Pet
}

func (d *Dog) speak() {
	fmt.Print("Wang")
}

//func (d *Dog) speakTo(name string) {
//	d.speak()
//	fmt.Print("Dog speak:" + name)
//}

func TestPet(t *testing.T) {
	dog := new(Dog)
	dog.speakTo("Li")
}

上述实现继承的关键为Dog结构体中包含的Pet。在Dog中重写了两个方法,但是在运行发现重写的speak并未被调用。

当打开下边的speakTo然后注释掉上边的speak方法后再次运行,会发现调用了重写的speakTo方法。

多态

package interface_test

import (
	"fmt"
	"testing"
)

type Programming interface {
	WriteHelloWorld() string
}

type GoProgramming struct {
}

func (g *GoProgramming) WriteHelloWorld() string {
	return "GO hello world!"
}

type JavaProgramming struct {
}

func (j *JavaProgramming) WriteHelloWorld() string {
	return "JAVA hello world!"
}

// 注意这里的Programming是一个指针参数
func firstWriteHelloWorld(p Programming) {
	world := p.WriteHelloWorld()
	fmt.Println(world)
}

func TestInteface(t *testing.T) {
	var gop Programming
	gop = new(GoProgramming)
	world := gop.WriteHelloWorld()
	t.Logf(world)
	javap := &JavaProgramming{}
	firstWriteHelloWorld(gop)
	firstWriteHelloWorld(javap)
}

猜你喜欢

转载自blog.csdn.net/h363659487/article/details/127271520