Multiple Inheritance
This lesson describes what multiple inheritance is and how Go achieves this via structs.
We'll cover the following...
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 implementation:
package mainimport "fmt"type Camera struct { }func (c *Camera) TakeAPicture() string { // method of Camerareturn "Click"}type Phone struct { }func (p *Phone ) Call() string { // method of Phonereturn "Ring Ring"}// multiple inheritancetype SmartPhone struct { // can use methods of both structsCameraPhone}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 with no fields. At line 6, there is a method that can be called only by a pointer that points to a Camera object. The method TakeAPicture returns a string Click. At line 10, we make a struct of type Phone with no fields. At line 12, there is a method that can be called only by a pointer pointing to a Phone object. The method Call just returns a string Ring Ring.
Now, we have a struct SmartPhone ...