Golang / GoLang Interfaces and Object Oriented Interview Questions
How does Go differ from classical OOP in terms of inheritance and method overriding?
Go deliberately omits classical inheritance. The Go FAQ explains this choice: inheritance creates tight coupling between classes, makes hierarchies rigid, and encourages deep class trees that are hard to refactor. Go replaces inheritance with composition and interfaces.
| OOP Concept | Go Equivalent | Notes |
|---|---|---|
| Class | struct + methods | No single keyword — type + methods on that type |
| Constructor | NewXxx() factory function | No special syntax — just a regular function |
| Inheritance | Struct embedding (composition) | Not IS-A, just method promotion |
| Method overriding | Shadow via embedding + own method | Outer method takes precedence; call inner explicitly |
| Abstract class | Interface + unexported concrete type + factory | Contract via interface, implementation hidden |
| Polymorphism | Interface dispatch (runtime) | Any type satisfying interface can be used |
| Protected | No equivalent | Go only has exported and unexported (package-private) |
| super() | Explicit embedded type call (EmbedType.Method()) | Must qualify explicitly — no super keyword |
// Go 'inheritance' via embedding â it's really composition type Base struct{ ID int } func (b Base) Identify() string { return fmt.Sprintf("ID=%d", b.ID) } type Derived struct { Base // promoted: Derived.Identify() â Base.Identify() Extra string } // 'Override' by defining the same method on Derived func (d Derived) Identify() string { // 'super().Identify()' equivalent: return d.Base.Identify() + " extra=" + d.Extra } d := Derived{Base: Base{ID: 1}, Extra: "foo"} fmt.Println(d.Identify()) // ID=1 extra=foo (Derived's method) fmt.Println(d.Base.Identify()) // ID=1 (Base's method) // CRITICAL: Derived is NOT a subtype of Base // This does NOT compile: // var b Base = d // cannot use Derived as type Base // They ARE both usable through a shared interface: type Identifier interface { Identify() string } var id Identifier = d // OK â Derived satisfies Identifier id = Base{ID: 2} // OK â Base satisfies Identifier too
More Related questions...