B
B
Bekkazy2019-06-21 14:52:23
go
Bekkazy, 2019-06-21 14:52:23

How to inherit and override one method in GO?

There is some python code. Implemented via OOP.

class Animal:
    def __init__(self, name):
        self.name = name

    def say(self):
        print("My name is", self.name)

    def eat(self):
        print("My name is", self.name, "and i eat grass")

    def walk(self):
        print("My name is", self.name, "and i jump")

    def start(self):
        self.say()
        self.eat()
        self.walk()


class Shark(Animal):
    def eat(self):
        print("My name is", self.name, "and i eat seals")

    def walk(self):
        print("My name is", self.name, "and i swim in the ocean")


if __name__ == '__main__':
    a = Animal("Kangaroo")
    a.start()
    print("------------------------")
    s = Shark("Shark")
    s.start()

It is very necessary to implement the same code on GO. I googled and couldn't find what I need. Maybe you have some tips?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Papa, 2019-06-21
Stifflera @PapaStifflera

Inheritance fails. There is no inheritance in Go.
Define the base type, embed it in the "successor" and override the desired method in the same place.

A
Alexander Lyamin, 2020-10-25
@genrih_md

You can write something like this, it will be very similar)

package main

import "fmt"

// Doer do
type Doer interface {
  eat()
}

// Animal is Animal
type Animal struct {
  name string
}

func (animal *Animal) eat() {
  fmt.Println("My name is", animal.name)
}

// Shark is Animal
type Shark struct {
  Animal
}

func (shark *Shark) eat() {
  fmt.Println("My name is", shark.name, "and i eat seals")
}

func start(doer Doer) {
  doer.eat()
}

func main() {
  animal := new(Animal)
  animal.name = "Kangaroo"
  start(animal)
  fmt.Println("-----------------------")
  shark := new(Shark)
  shark.name = "Shark"
  start(shark)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question