Golang / GoLang Interfaces and Object Oriented Interview Questions
How does Go implement encapsulation without private/public class modifiers?
Go's encapsulation is package-level, not class-level. Identifiers (types, fields, functions, methods) are exported (public) if they start with an uppercase letter, and unexported (package-private) if they start with a lowercase letter. There is no private, protected, or public keyword.
// package accounts // Exported type â usable outside the package type Account struct { owner string // unexported â only accessible within package accounts balance float64 // unexported ID int // exported field } // Constructor (factory function) â controls how Account is created func NewAccount(owner string, initialBalance float64) (*Account, error) { if initialBalance < 0 { return nil, fmt.Errorf("initial balance cannot be negative") } return &Account{owner: owner, balance: initialBalance}, nil } // Exported getter func (a *Account) Balance() float64 { return a.balance } func (a *Account) Owner() string { return a.owner } // Exported mutator with validation func (a *Account) Deposit(amount float64) error { if amount <= 0 { return fmt.Errorf("deposit amount must be positive") } a.balance += amount return nil } // In main package: acc, _ := accounts.NewAccount("Alice", 100.0) fmt.Println(acc.Balance()) // 100.0 â OK // acc.balance = 9999 // COMPILE ERROR: acc.balance is unexported // acc.owner = "Hacker" // COMPILE ERROR acc.Deposit(50.0) // OK â goes through validation
Differences from Java/C++: Go has no protected — there is no concept of subclass access. Unexported fields are invisible even to embedding structs in other packages. The internal package mechanism provides a stronger form of encapsulation: code in foo/internal/bar can only be imported by code rooted at foo.
More Related questions...