How to override methods in Child, but called in Parent?

type A struct {
}

func NewA() *A {
	return &A{}
}

func (a *A) Foo() {
	fmt.Println("Foo of A")
}

func (a *A) Bar() {
	//More codes...
	a.Foo()
	//More codes...
}

type B struct {
	*A
}

func NewB() *B {
	return &B{
		A: NewA(),
	}
}

func (b *B) Foo() {
	fmt.Println("Foo of B")
}

func main() {
	b := NewB()
	b.Bar()
}

I want to override the Foo() method in B, and let B inherit all things A has
When calling b.Bar(), I think it should print:

Foo of B

But it does not.

In Java, it works like this:


public class Main {

    class A {
        public void foo() {
            System.out.println("Foo of A");
        }

        public void bar() {
            foo();
        }

    }

    class B extends A {
        public void foo() {
            System.out.println("Foo of B");
        }
    }

    public void Test01() {
        B b = new B();
        b.bar();
    }

    public static void main(String[] args) {
        Main m = new Main();
        m.Test01();
    }
}

Go doesn’t really work like that. It has no inheritance in the OOP sense like Java. If you’re coming from that background, this talk might be helpful to understand better how Go deals with the subject: GopherCon Europe 2022: Yarden Laifenfeld - From OOP to Go - YouTube

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.