go的匿名组合

golang也提供了继承机制,但采用组合的文法,因此称为匿名组合。与其他语言不同, golang很清晰地展示出类的内存布局是怎样的。

一  非指针方式的组合

 1)基本语法

type base struct{
	//成员变量
}

func(b *base) 函数名(参数列表)(返回值列表){
	//函数体
}

//派生类
type derived struct{
	base
	//成员变量
}

func (b *derived) 函数名(参数列表)(返回值列表){
	//函数体
}

2)继承规则

 在派生类没有改写基类的成员方法时,相应的成员方法被继承。

        派生类可以直接调用基类的成员方法,譬如基类有个成员方法为Base.Func(),那么Derived.Func()等同于Derived.Base.Func()

        倘若派生类的成员方法名与基类的成员方法名相同,那么基类方法将被覆盖或叫隐藏,譬如基类和派生类都有成员方法Func(),那么Derived.Func()将只能调用派生类的Func()方法,如果要调用基类版本,可以通过Derived.Base.Func()来调用。

举例如下:

package main

import "fmt"

type Base struct{
	//成员变量
}

func(b *Base) Func1(){

	fmt.Println("Base.Func1 was invoked1")

}

func(b *Base) Func2(){

	fmt.Println("Base.Func2 was invoked1")

}

//派生类
type Derived struct{
	Base
	//成员变量
}

func (d *Derived) Func2(){
	fmt.Println("Derived.Func2() was invoked!")
}


func (d *Derived) Func3(){
	fmt.Println("Derived.Func3() was invoked!")
}

func main(){
	d:=&Derived{}
	d.Func1()
	d.Base.Func1()
	d.Func2()
	d.Base.Func2()
	d.Func3()
}

二  指针组合模式

基本语法:

/ 基类
type Base struct {
    // 成员变量
}

func (b *Base) 函数名(参数列表) (返回值列表) {
    // 函数体
}

// 派生类
type Derived struct {
    *Base
    // 成员变量
}

func (b *Derived) 函数名(参数列表) (返回值列表) {
    // 函数体
}

猜你喜欢

转载自www.cnblogs.com/aomi/p/9249703.html