golang没有类,只有struct,但也可以做到类的效果,如:
type Animal struct {
Name string
Weight string
}
func (a *Animal) Eat(food string) {
fmt.Printf("%s eat some food %s\n", a.Name, food)
}
go使用组合的形式实现了代码重用,当一个结构体包含了另一个结构体,那么外面的结构体就拥有里面结构体的所有成员变量和 方法 ,这就有点类似于继承了:
type Bird struct {
Animal
}
func (b *Bird) Fly() {
fmt.Println("I'm flying")
}
func (b *Bird) Eat(food string) {
fmt.Println("bird eat...")
}
Bird有Animal的一切属性和方法,还有自己的方法,并覆盖了父类的方法Eat,再看如何调用:
func main() {
var b Bird
b.Name = "bird"
b.Eat("nut")
b.Animal.Eat("leaf")
}
输出:
bird eat...
bird eat some food leaf
可见Bird覆盖了父类方法,如要调用父类方法,则需这样调用b.Animal.Eat("leaf")。可以把Bird的Eat方法参数去掉:
func (b *Bird) Eat() {
fmt.Println("bird eat...")
}
有点重载的味道了。
能否继承其他包的struct,并覆盖它的方法呢?
base.go代码:
package base
import "fmt"
type Base struct {
Name string
}
func (b *Base) Print() {
fmt.Println("this is base class print")
}
再“继承”和覆盖父类方法,
type Child struct {
base.Base
}
func (c *Child) Print() {
fmt.Println("this is child class print")
}
调用:
func main() {
c := Child{}
c.Base.Print()
c.Print()
}
输出:
this is base class print
this is child class print
可见是一样的。
go虽然没有类的概念,可是也有面向对象的元素和方式,继承、封装、多态,都齐全。
本文详细介绍了Golang中如何通过结构体和方法实现面向对象编程,包括代码重用、方法覆盖及多态特性,展示了Go语言虽无传统类概念,但仍能实现类似面向对象的功能。

292

被折叠的 条评论
为什么被折叠?



