Sobes.tech
Junior — Middle

Explain the mechanism and features of inheritance in object-oriented programming.

sobes.tech AI

Answer from AI

Object-oriented programming (OOP) allows creating a new class based on an existing one, inheriting its properties and methods. This promotes code reuse and hierarchical organization of objects.

Features of inheritance:

  • Class hierarchy: a subclass (child) extends or overrides the behavior of a superclass (parent).
  • Polymorphism: objects of a subclass can be used where a superclass object is expected.
  • Encapsulation: inheritance does not violate the principle of data hiding, but the subclass has access to protected and public members of the superclass.

In Go, there is no direct inheritance of classes, but composition and interfaces are used to implement similar patterns.

Example in Go with composition:

type Animal struct {
    Name string
}

func (a Animal) Speak() string {
    return "..."
}

// Dog "inherits" Animal through embedding
// and can override the Speak method

type Dog struct {
    Animal
}

func (d Dog) Speak() string {
    return "Woof!"
}

func main() {
    dog := Dog{Animal{Name: "Buddy"}}
    fmt.Println(dog.Name)      // Buddy
    fmt.Println(dog.Speak())   // Woof!
}
Explain the mechanism and features of inheritance in… - sobes.tech