Sobes.tech
Senior

Tell me more about OOP and its main principles (polymorphism, interfaces)

sobes.tech AI

Answer from AI

Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which combine data and methods for working with that data.

Main principles of OOP:

  • Encapsulation — combining data and methods into a single object, hiding internal implementation, and providing an interface for interaction.
  • Inheritance — the ability to create new types based on existing ones, inheriting their properties and behaviors.
  • Polymorphism — the ability for objects of different types to be processed through a common interface, allowing the same code to be used for different types.

In Go, there is no classical OOP with inheritance, but interfaces and composition allow implementing polymorphism and abstraction.

Polymorphism in Go is achieved through interfaces — a set of methods that a type must implement. Any type that implements the interface methods automatically satisfies the interface.

Example of interface and polymorphism in Go:

package main
import "fmt"

type Speaker interface {
    Speak() string
}

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

type Cat struct {}
func (c Cat) Speak() string {
    return "Meow!"
}

func makeSpeak(s Speaker) {
    fmt.Println(s.Speak())
}

func main() {
    d := Dog{}
    c := Cat{}
    makeSpeak(d) // Woof!
    makeSpeak(c) // Meow!
}

Thus, interfaces in Go allow writing flexible and extensible code without a rigid class hierarchy.

Tell me more about OOP and its main principles… - sobes.tech