目录
1.Go语言中的面对对象多态的实现---interface
Go语言中,一样支持接口,我们先通过一个例子来快速学习Go语言的接口实现方式:
package main
import "fmt"
// 定义一个Animal接口,其定义了三个方法Walk, Run ,ShowColor(父类指针)
type Animal interface {
Walk()
Run()
ShowColor()
}
// 定义一个狗类(具体的类),实现了Animal接口的所有方法
type Dog struct {
Color string
}
func (this *Dog) Walk() {
fmt.Println("the dog is walk")
}
func (this *Dog) Run() {
fmt.Println("the dog is run")
}
func (this *Dog) ShowColor() {
fmt.Println("the dog color is ", this.Color)
}
func main() {
var ani Animal
ani = &Dog{"yellow"}
ani.Walk()
ani.Run()
ani.ShowColor()
}
运行结果:
the dog is walk
the dog is run
the dog color is yellow
可以看到,使用父类指针ani(Animal指针)就可以调用实现该类接口的Dog类对象的方法,Go语言中,并不要显示的说明一个类实现了哪个接口的方法,只要实现了该接口的所有方法即可以认为该类是该接口的实现类,进一步说,只有实现了该接口的所有方法才会被认为是该接口的实现类,我们可以做一个简单的测试:
package main
import "fmt"
// 定义一个Animal接口,其定义了三个方法Walk, Run ,ShowColor(父类指针)
type Animal inte