Search⌘ K
AI Features

Multiple Inheritance

Explore how Go supports multiple inheritance by embedding multiple structs within a new type. Learn how to call methods from embedded types and understand the use of idiomatic method names and interfaces to achieve polymorphism without classic class hierarchies. This lesson helps you grasp Go's unique approach to object-oriented programming concepts.

Multiple inheritance is the ability for a type to obtain the behaviors of more than one parent class. In classical OO languages, it is usually not implemented (exceptions are C++ and Python), because, in class-based hierarchies, it introduces additional complexities for the compiler. But in Go, multiple inheritance can be implemented simply by embedding all the necessary ‘parent’ types in the type under construction.

Look at the following ...

Go (1.6.2)
package main
import "fmt"
type Camera struct { }
func (c *Camera) TakeAPicture() string { // method of Camera
return "Click"
}
type Phone struct { }
func (p *Phone ) Call() string { // method of Phone
return "Ring Ring"
}
// multiple inheritance
type SmartPhone struct { // can use methods of both structs
Camera
Phone
}
func main() {
cp := new(SmartPhone)
fmt.Println("Our new SmartPhone exhibits multiple behaviors ...")
fmt.Println("It exhibits behavior of a Camera: ", cp.TakeAPicture())
fmt.Println("It works like a Phone too: ", cp.Call())
}

In the above code, at line 4, we make a struct of type Camera ...