Inheritance is a fundamental concept in object-oriented programming that allows a subclass to inherit all the properties and behaviors of its superclass. Inheritance promotes code reuse and simplifies the codebase, making it more manageable and easier to maintain.

However, Golang does not support inheritance in the traditional sense. Instead of inheritance, Golang supports composition, which is a way to build complex types from simpler ones by combining them. Composition provides similar benefits to inheritance while promoting better code organization and reusability.

Composition in Golang

Composition example

The following program demonstrates how to use composition to create a new type that combines the functionality of two existing types.

package main

import "fmt"

type Animal struct {
    name string
}

func (a *Animal) Speak() {
    fmt.Println("Hello, I'm", a.name)
}

type Pet struct {
    animal *Animal
    owner  string
}

func (p *Pet) Speak() {
    p.animal.Speak()
    fmt.Println("My owner is", p.owner)
}

func main() {
    a := &Animal{name: "Fluffy"}
    p := &Pet{animal: a, owner: "John"}

    p.Speak()
}

In the above program, we define two types, Animal and Pet. The Animal type has a single field, name, and a method, Speak(), that prints a message to the console. The Pet type is composed of an Animal object and an owner field. The Pet type also has a method, Speak(), that calls the Speak() method of the embedded Animal object and prints the name of the owner.

When we create a new Pet object, we pass in a pointer to an Animal object and the name of the owner. The resulting Pet object has all the fields and methods of both the Animal and Pet types.

golang inheritance

Exercises

  1. Create a new type that composes two existing types.
  2. Modify the Pet type to include a method that changes the owner’s name.
  3. Create a new method on the Animal type that prints the name in all uppercase letters.