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 validationDifferences 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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
