Inheritance — and Why Go Uses Embedding Instead
Definition
Inheritance
- In plain English
- Inheritance is when one class automatically gets the fields and methods of a parent class.
- Think of it like
- It is like a child inheriting family traits from a parent.
Embedding
- In plain English
- Embedding places one struct inside another so the outer struct can use the inner one's fields and methods directly.
- Think of it like
- It is like a phone with a built-in camera, which can take photos because it contains a camera, not because it is one.
Why it exists
class Device {}
class Wearable extends Device {}
class Watch extends Wearable {}
class SmartWatch extends Watch {}
class SmartWatchWithGPS extends SmartWatch {}Now you need a GPS tracker that is not a watch. The existing family tree gives GPS no clean home. You either duplicate it or reshape several parent classes.
Fragile base class
- In plain English
- The fragile base class problem is when a parent-class change unexpectedly breaks classes built on it.
- Think of it like
- It is like changing a building’s foundation and cracking every floor above.
How it works
class Vessel {
constructor(public name: string) {}
describe(): string { return `Vessel ${this.name}`; }
}
class Ferry extends Vessel {}Method promotion
- In plain English
- Method promotion means you can call an embedded type’s methods directly on the outer type, as if they were its own.
- Think of it like
- It is like a receptionist answering the phone on behalf of the whole office.
package main
import "fmt"
type Vessel struct{ Name string }
func (v Vessel) Describe() string { return "Vessel " + v.Name }
type Ferry struct {
Vessel
CarSlots int
}
func main() {
f := Ferry{Vessel: Vessel{Name: "Harbour"}, CarSlots: 40}
fmt.Println(f.Describe())
}
FerryInherits extends Vessel through class inheritance. In contrast, Go's Ferry contains a Vessel through embedding.
- If Ferry declares Describe, f.Describe() selects that method.
- f.Vessel.Describe() still calls the embedded value’s method.
- Calls inside Vessel's methods still use Vessel's methods, even if Ferry defines methods with the same names.
- If two embedded types provide the same name, choose the field: f.Vessel.Describe().
Examples
Reuse and substitution are separate
Booking can describe ferries and cargo ships through the same interface.
package main
import "fmt"
type Vessel struct{ Name string }
func (v Vessel) Describe() string { return "Vessel " + v.Name }
type Ferry struct {
Vessel
CarSlots int
}
type CargoShip struct {
Vessel
Tonnes int
}
type Describer interface{ Describe() string }
func Book(d Describer) { fmt.Println(d.Describe()) }
func main() {
f := Ferry{Vessel: Vessel{Name: "Harbour"}, CarSlots: 40}
Book(f)
Book(CargoShip{Vessel: Vessel{Name: "Freight"}, Tonnes: 800})
}
Ferry is a different type from Vessel. Book accepts either through Describer because it only needs the Describe method.
The insight
Embedding reuses code; interfaces let different types answer the same call.
Shared exhibit fields
Audio and video exhibits share an ID and title. Each provides its own Play method.
package main
import "fmt"
type Exhibit struct{ ID, Title string }
type AudioExhibit struct{ Exhibit }
func (a AudioExhibit) Play() { fmt.Println("audio", a.Title) }
type VideoExhibit struct{ Exhibit }
func (v VideoExhibit) Play() { fmt.Println("video", v.Title) }
type Playable interface{ Play() }
func main() {
items := []Playable{AudioExhibit{Exhibit{"A1", "Bells"}}, VideoExhibit{Exhibit{"V1", "Waves"}}}
for _, item := range items {
item.Play()
}
}
The common field holder does not need a Play method. AudioExhibit and VideoExhibit implement that operation themselves.
The insight
Shared fields come from embedding; shared behaviour comes through interfaces.
Choose device capabilities
A running watch needs heart rate, GPS and a display. A tracking tag needs GPS alone.
RunningWatch contains HeartRate, GPS and Display parts. GPSTag contains only a GPS part.
Keep GPS separate from watch behaviour. A new device uses GPS without joining the watch family tree.
The insight
Mix capabilities instead of forcing a single family tree.
Trade-offs
Pros
- Reuse without a rigid class hierarchy.
- Pick the capabilities a type needs.
- Avoid methods inherited through many parent classes.
Cons
- Embedding does not make Ferry interchangeable with Vessel.
- Promoted names can clash.
- Changes to an embedded type can still affect callers.
Use when
- Reusing fields and behaviour with a meaningful contained type.
- Direct access to the embedded methods helps callers.
Avoid when
- You only need types to answer the same calls; use an interface.
- You need to hide the contained methods; use a named field.
Quick check
Takeaways
- Inheritance shares code through a family tree.
- Go embeds instead.
- Embed for reuse; use interfaces when one type must stand in for another.