What are the main principles of object-oriented programming you know and use?
sobes.tech AI
Answer from AI
The main principles of object-oriented programming (OOP) that I use:
-
Encapsulation — combining data and methods that work with this data into a single object, as well as hiding the internal implementation from the outside world. In Go, this is achieved through exported and unexported fields and methods.
-
Inheritance — the ability to create new types based on existing ones. In Go, there is no direct inheritance, but composition (embedding structs) can be used for code reuse.
-
Polymorphism — the ability for objects of different types to be processed through a single interface. In Go, this is implemented via interfaces.
-
Abstraction — highlighting the essential characteristics of an object, hiding implementation details.
An example in Go using interfaces and composition:
package main
import "fmt"
type Speaker interface {
Speak() string
}
type Animal struct {
Name string
}
func (a Animal) Speak() string {
return "..."
}
// Cat "inherits" Animal through embedding
type Cat struct {
Animal
}
func (c Cat) Speak() string {
return "Meow"
}
func main() {
var s Speaker = Cat{Animal{Name: "Kitty"}}
fmt.Println(s.Speak()) // Meow
}
Thus, Go supports the main concepts of OOP but implements them through its idioms — interfaces and composition.