golang能像java一样实现接口的重写吗,答案是可以的,看下面这波操作

type Test interface {
	a()
	b()
}

type TestCommon struct {}

func (t TestCommon)a() {
	fmt.Println("this TestCommon.a()")

}
func (t TestCommon)b() {
	fmt.Println("this TestCommon.b()")
}

type TestShade struct{
	TestCommon
}

func (t TestShade)a() {
	fmt.Println("this is TestShade.a()")
}
func main() {
	var x Test = TestShade{}
	x.a()  //this is TestShade.a()
	x.b()  //this TestCommon.b()
}

我们定义了Test接口,然后TestCommon实现了这个接口,我们在定义了一个类型TestShade,他包含了TestCommon这个类型的一个属性。这样我们的TestShade也就间接实现了Test接口,这时候我们用TestShade重写Test的接口,就能实现对TestCommon的实现方式的重写

但是这里有一个限制,就是TestShade里面不能有两个属性同时实现Test接口,不然会报错的

type Test interface {
	a()
	b()
}

type TestCommon struct {}

func (t TestCommon)a() {
	fmt.Println("this TestCommon.a()")

}
func (t TestCommon)b() {
	fmt.Println("this TestCommon.b()")
}

type TestCommon1 struct {}

func (t TestCommon1)a() {
	fmt.Println("this TestCommon.a()")

}
func (t TestCommon1)b() {
	fmt.Println("this TestCommon.b()")
}

type TestShade struct{
	TestCommon
	TestCommon1
}

func (t TestShade)a() {
	fmt.Println("this is TestShade.a()")
}

func main() {
	var x Test = TestShade{}
	x.a()
	x.b()

}

在这里插入图片描述
逻辑上面也能想明白,如果有两个类型都实现了Test接口,那么我们就不知道这里的b方法到底该调用TestCommon的TestCommon1的b().
当然如果你把a()和b()都覆盖掉的话就没问题了。

type Test interface {
	a()
	b()
}

type TestCommon struct {}

func (t TestCommon)a() {
	fmt.Println("this TestCommon.a()")

}
func (t TestCommon)b() {
	fmt.Println("this TestCommon.b()")
}

type TestCommon1 struct {}

func (t TestCommon1)a() {
	fmt.Println("this TestCommon1.a()")

}
func (t TestCommon1)b() {
	fmt.Println("this TestCommon1.b()")
}

type TestShade struct{
	TestCommon
	TestCommon1
}

func (t TestShade)a() {
	fmt.Println("this is TestShade.a()")
}

func (t TestShade)b() {
	fmt.Println("this is TestShade.b()")
}
func main() {
	var x Test = TestShade{}
	x.a()  //this is TestShade.a()
	x.b()  //this is TestShade.b()
}