Sobes.tech
Junior — Middle

Can you explain the principle of encapsulation and how it is implemented in object-oriented programming?

sobes.tech AI

Answer from AI

Encapsulation is a principle of object-oriented programming that involves hiding the internal implementation of an object and providing access to data and methods only through a defined interface.

This allows:

  • Protecting data from incorrect usage
  • Hiding implementation complexity
  • Ensuring control over the modification of the object's state

In OOP languages, encapsulation is implemented using access modifiers (e.g., private, protected, public), which determine which fields and methods are accessible from outside.

Example in Go (where encapsulation is achieved through exported and unexported identifiers):

type User struct {
    name string // unexported field, accessible only within the package
}

func (u *User) GetName() string {
    return u.name // public method to access the name
}

func (u *User) SetName(newName string) {
    if newName != "" {
        u.name = newName
    }
}

Here, the 'name' field is hidden from external access, and interaction with it occurs through the GetName and SetName methods, which control access logic and modifications.

Can you explain the principle of encapsulation and… - sobes.tech