Encapsulation — Data Hiding Done Right
Introduction
Classes and Objects — Blueprint vs Instance and Constructors — Default, Parameterized, Copy showed how to define a class, make objects from it and check their values in the constructor. That check runs once, when the object is made. What happens after that?
Take a bank account whose constructor refuses a negative balance. If its balance is an ordinary public attribute, any code can still do this:
account = BankAccount("Alice", 1000.0) # the constructor checked these values
account.balance = -5000 # and nothing checks this oneIt is like a bank that checks your ID at the door and then leaves the vault open. Encapsulation closes the vault. It means two things together: keeping an object's data hidden from outside code, and offering methods as the only way to change that data, each checking the change before making it.
It matters most in code that many people change. When the data can only be changed through the object's own methods, a teammate's new code cannot slip past the object's rules, because the rules sit in one place and every change passes through them.
The Problem Without Encapsulation
Here is what goes wrong when the data is left open. The account's withdraw checks the amount, but nothing makes other code use it:
# No encapsulation: every attribute is public
class BankAccountUnsafe:
def __init__(self, owner: str, balance: float) -> None:
self.owner = owner
self.balance = balance
def withdraw(self, amount: float) -> None:
if amount > self.balance:
print("Insufficient funds!")
return
self.balance -= amount
account = BankAccountUnsafe("Alice", 1000.0)
# Any code can skip withdraw() and its check, and write whatever it likes
account.balance = -99999.0 # a negative balance
account.owner = "" # an account with no owner
print(f"Owner: '{account.owner}', balance: ${account.balance:.2f}")
# The check inside withdraw() protects nothing while anyone can change balance directlyimport java.util.Locale;
// No encapsulation: every field is public
public class BankAccountUnsafe {
public String owner;
public double balance;
public BankAccountUnsafe(String owner, double balance) {
this.owner = owner;
this.balance = balance;
}
public void withdraw(double amount) {
if (amount > balance) {
System.out.println("Insufficient funds!");
return;
}
balance -= amount;
}
public static void main(String[] args) {
BankAccountUnsafe account = new BankAccountUnsafe("Alice", 1000.0);
// Any code can skip withdraw() and its check, and write whatever it likes
account.balance = -99999.0; // a negative balance
account.owner = ""; // an account with no owner
System.out.printf(Locale.ROOT, "Owner: '%s', balance: $%.2f%n",
account.owner, account.balance);
// The check inside withdraw() protects nothing while anyone can change balance
}
}#include <cstdio>
#include <string>
#include <utility>
// No encapsulation: every member is public
class BankAccountUnsafe {
public:
std::string owner;
double balance;
BankAccountUnsafe(std::string owner, double balance)
: owner(std::move(owner)), balance(balance) {}
void withdraw(double amount) {
if (amount > balance) {
std::printf("Insufficient funds!\n");
return;
}
balance -= amount;
}
};
int main() {
BankAccountUnsafe account("Alice", 1000.0);
// Any code can skip withdraw() and its check, and write whatever it likes
account.balance = -99999.0; // a negative balance
account.owner = ""; // an account with no owner
std::printf("Owner: '%s', balance: $%.2f\n", account.owner.c_str(),
account.balance);
// The check inside withdraw() protects nothing while anyone can change balance
return 0;
}// No encapsulation: every field is public
class BankAccountUnsafe {
owner: string;
balance: number;
constructor(owner: string, balance: number) {
this.owner = owner;
this.balance = balance;
}
withdraw(amount: number): void {
if (amount > this.balance) {
console.log("Insufficient funds!");
return;
}
this.balance -= amount;
}
}
const account = new BankAccountUnsafe("Alice", 1000.0);
// Any code can skip withdraw() and its check, and write whatever it likes
account.balance = -99999.0; // a negative balance
account.owner = ""; // an account with no owner
console.log(`Owner: '${account.owner}', balance: $${account.balance.toFixed(2)}`);
// The check inside withdraw() protects nothing while anyone can change balanceusing System;
using static System.FormattableString;
// No encapsulation: every field is public
public class BankAccountUnsafe
{
public string Owner;
public double Balance;
public BankAccountUnsafe(string owner, double balance)
{
Owner = owner;
Balance = balance;
}
public void Withdraw(double amount)
{
if (amount > Balance)
{
Console.WriteLine("Insufficient funds!");
return;
}
Balance -= amount;
}
}
public static class Program
{
public static void Main()
{
var account = new BankAccountUnsafe("Alice", 1000.0);
// Any code can skip Withdraw() and its check, and write whatever it likes
account.Balance = -99999.0; // a negative balance
account.Owner = ""; // an account with no owner
Console.WriteLine(
Invariant($"Owner: '{account.Owner}', balance: ${account.Balance:F2}"));
// The check inside Withdraw() protects nothing while anyone can change Balance
}
}package main
import "fmt"
// BankAccountUnsafe has no encapsulation: in Go a capital letter makes a field public
type BankAccountUnsafe struct {
Owner string
Balance float64
}
func NewBankAccountUnsafe(owner string, balance float64) *BankAccountUnsafe {
return &BankAccountUnsafe{Owner: owner, Balance: balance}
}
func (a *BankAccountUnsafe) Withdraw(amount float64) {
if amount > a.Balance {
fmt.Println("Insufficient funds!")
return
}
a.Balance -= amount
}
func main() {
account := NewBankAccountUnsafe("Alice", 1000.0)
// Any code can skip Withdraw() and its check, and write whatever it likes
account.Balance = -99999.0 // a negative balance
account.Owner = "" // an account with no owner
fmt.Printf("Owner: '%s', balance: $%.2f\n", account.Owner, account.Balance)
// The check inside Withdraw() protects nothing while anyone can change Balance
}It prints:
Owner: '', balance: $-99999.00
Two plain assignments left an account with no owner and a balance of minus 99,999, and the check inside withdraw was never asked. In Python a public attribute can even be given a string. Public data can be changed to anything, at any time, by any code, around every rule the class has.
The picture sets this account beside one that keeps its data to itself.

Access Modifiers: Controlling Visibility
Every language has some way to say who may reach an attribute or a method. Java has four access levels, and its tutorial gives each one's reach in a table; Python has no access keywords at all, only naming habits.
| Java modifier | Who can reach the member | Nearest Python habit |
|---|---|---|
public | Its class, its package, its subclasses, and any other code | name: public, the default |
protected | Its class, its package and its subclasses | _name: internal, by convention only |
| no modifier | Its class and its package | no such level |
private | Its own class only | __name: renamed, still reachable |
Note that protected in Java reaches the whole package as well as subclasses, and that leaving the modifier out gives a level of its own, package access. The Java tutorial says it plainly: "The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package." and "The private modifier specifies that the member can only be accessed in its own class."
Java enforces this when the code is compiled. A line outside BankAccount that writes its private balance does not compile; javac stops with balance has private access in BankAccount.
Python relies on names and on the people reading them. Its tutorial says "“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python." A single leading underscore, as in _name, is only a signal: PEP 8, Python's style guide, calls it a weak indicator of "internal use". Two leading underscores make Python rename the attribute: Python's tutorial explains that a name such as __spam inside a class is replaced with _classname__spam. That guards against accidents, and Python's tutorial adds that "it still is possible to access or modify a variable that is considered private." A small lab on the safe account below showed both sides: account.balance = -5000 failed with AttributeError: property 'balance' of 'BankAccount' object has no setter, while a write of -5000 to the renamed attribute, _BankAccount__balance, went through and left the balance at -5000.
The idea is the same in both languages: keep the data private and show outside code only what it needs.
Encapsulation in Practice: The Safe Bank Account
Here is BankAccount rebuilt with its data kept to itself. The data is private, outside code can read it but not write it, and every change goes through a method that checks the change first. Each language marks the data private in its own way, named in a comment: two underscores in Python, private in Java, C++ and TypeScript, a property with a private setter in C#, and a lowercase name in Go, which hides by package rather than by class.
class BankAccount:
"""A bank account that keeps its data to itself: encapsulation."""
def __init__(self, owner: str, balance: float = 0.0) -> None:
if not owner.strip():
raise ValueError("Owner name cannot be empty")
if balance < 0:
raise ValueError("Initial balance cannot be negative")
# Two leading underscores: Python renames these inside the class (name mangling)
self.__owner = owner.strip()
self.__balance = balance
self.__is_frozen = False
# Read-only views of the private data: properties with no setter
@property
def owner(self) -> str:
return self.__owner
@property
def balance(self) -> float:
return self.__balance
@property
def is_frozen(self) -> bool:
return self.__is_frozen
# The only ways to change the balance, each checking the account's rules first
def deposit(self, amount: float) -> None:
if self.__is_frozen:
raise RuntimeError("Cannot deposit into a frozen account")
if amount <= 0:
raise ValueError("Deposit amount must be positive")
self.__balance += amount
print(f"Deposited ${amount:.2f}. New balance: ${self.__balance:.2f}")
def withdraw(self, amount: float) -> None:
if self.__is_frozen:
raise RuntimeError("Cannot withdraw from a frozen account")
if amount <= 0:
raise ValueError("Withdrawal amount must be positive")
if amount > self.__balance:
raise ValueError(
f"Insufficient funds: ${amount:.2f} > ${self.__balance:.2f}")
self.__balance -= amount
print(f"Withdrew ${amount:.2f}. New balance: ${self.__balance:.2f}")
def freeze(self) -> None:
self.__is_frozen = True
print(f"Account for {self.__owner} is now FROZEN.")
account = BankAccount("Alice", 1000.0)
print(f"Owner: {account.owner}")
print(f"Balance: ${account.balance:.2f}")
account.deposit(500.0)
account.withdraw(200.0)
# account.balance = -5000 would fail: balance has no setter
# Every attempt to break the rules is refused by the object itself
try:
account.withdraw(-100)
except ValueError as e:
print(f"Blocked: {e}")
try:
account.withdraw(99999)
except ValueError as e:
print(f"Blocked: {e}")
account.freeze()
try:
account.deposit(100)
except RuntimeError as e:
print(f"Blocked: {e}")import java.util.Locale;
// A bank account that keeps its data to itself: encapsulation
public class BankAccount {
// Private fields: no code outside this class can read or write them
private final String owner;
private double balance;
private boolean isFrozen;
public BankAccount(String owner, double balance) {
if (owner == null || owner.trim().isEmpty()) {
throw new IllegalArgumentException("Owner name cannot be empty");
}
if (balance < 0) {
throw new IllegalArgumentException("Initial balance cannot be negative");
}
this.owner = owner.trim();
this.balance = balance;
this.isFrozen = false;
}
// Read-only views of the private data: getters, and no setters
public String getOwner() {
return owner;
}
public double getBalance() {
return balance;
}
public boolean isFrozen() {
return isFrozen;
}
// The only ways to change the balance, each checking the account's rules first
public void deposit(double amount) {
if (isFrozen) {
throw new IllegalStateException("Cannot deposit into a frozen account");
}
if (amount <= 0) {
throw new IllegalArgumentException("Deposit amount must be positive");
}
balance += amount;
System.out.printf(Locale.ROOT, "Deposited $%.2f. New balance: $%.2f%n",
amount, balance);
}
public void withdraw(double amount) {
if (isFrozen) {
throw new IllegalStateException("Cannot withdraw from a frozen account");
}
if (amount <= 0) {
throw new IllegalArgumentException("Withdrawal amount must be positive");
}
if (amount > balance) {
throw new IllegalArgumentException(String.format(Locale.ROOT,
"Insufficient funds: $%.2f > $%.2f", amount, balance));
}
balance -= amount;
System.out.printf(Locale.ROOT, "Withdrew $%.2f. New balance: $%.2f%n",
amount, balance);
}
public void freeze() {
isFrozen = true;
System.out.println("Account for " + owner + " is now FROZEN.");
}
public static void main(String[] args) {
BankAccount account = new BankAccount("Alice", 1000.0);
System.out.println("Owner: " + account.getOwner());
System.out.printf(Locale.ROOT, "Balance: $%.2f%n", account.getBalance());
account.deposit(500.0);
account.withdraw(200.0);
// account.balance = -5000; would not compile: balance is private
// Every attempt to break the rules is refused by the object itself
try {
account.withdraw(-100);
} catch (IllegalArgumentException e) {
System.out.println("Blocked: " + e.getMessage());
}
try {
account.withdraw(99999);
} catch (IllegalArgumentException e) {
System.out.println("Blocked: " + e.getMessage());
}
account.freeze();
try {
account.deposit(100);
} catch (IllegalStateException e) {
System.out.println("Blocked: " + e.getMessage());
}
}
}#include <cstdio>
#include <stdexcept>
#include <string>
// A bank account that keeps its data to itself: encapsulation
class BankAccount {
public:
BankAccount(const std::string& owner, double balance)
: owner_(owner), balance_(balance), isFrozen_(false) {
if (owner.find_first_not_of(" \t\n") == std::string::npos) {
throw std::invalid_argument("Owner name cannot be empty");
}
if (balance < 0) {
throw std::invalid_argument("Initial balance cannot be negative");
}
}
// Read-only views of the private data: getters, and no setters
const std::string& getOwner() const { return owner_; }
double getBalance() const { return balance_; }
bool isFrozen() const { return isFrozen_; }
// The only ways to change the balance, each checking the account's rules first
void deposit(double amount) {
if (isFrozen_) {
throw std::logic_error("Cannot deposit into a frozen account");
}
if (amount <= 0) {
throw std::invalid_argument("Deposit amount must be positive");
}
balance_ += amount;
std::printf("Deposited $%.2f. New balance: $%.2f\n", amount, balance_);
}
void withdraw(double amount) {
if (isFrozen_) {
throw std::logic_error("Cannot withdraw from a frozen account");
}
if (amount <= 0) {
throw std::invalid_argument("Withdrawal amount must be positive");
}
if (amount > balance_) {
char message[96];
std::snprintf(message, sizeof message, "Insufficient funds: $%.2f > $%.2f",
amount, balance_);
throw std::invalid_argument(message);
}
balance_ -= amount;
std::printf("Withdrew $%.2f. New balance: $%.2f\n", amount, balance_);
}
void freeze() {
isFrozen_ = true;
std::printf("Account for %s is now FROZEN.\n", owner_.c_str());
}
private:
// Private members: no code outside this class can read or write them
std::string owner_;
double balance_;
bool isFrozen_;
};
int main() {
BankAccount account("Alice", 1000.0);
std::printf("Owner: %s\n", account.getOwner().c_str());
std::printf("Balance: $%.2f\n", account.getBalance());
account.deposit(500.0);
account.withdraw(200.0);
// account.balance_ = -5000; would not compile: balance_ is private
// Every attempt to break the rules is refused by the object itself
for (double amount : {-100.0, 99999.0}) {
try {
account.withdraw(amount);
} catch (const std::invalid_argument& e) {
std::printf("Blocked: %s\n", e.what());
}
}
account.freeze();
try {
account.deposit(100);
} catch (const std::logic_error& e) {
std::printf("Blocked: %s\n", e.what());
}
return 0;
}// A bank account that keeps its data to itself: encapsulation
class BankAccount {
// Private fields: code outside this class that names them does not compile
private readonly owner: string;
private balance: number;
private frozen: boolean;
constructor(owner: string, balance: number = 0) {
if (!owner.trim()) {
throw new Error("Owner name cannot be empty");
}
if (balance < 0) {
throw new Error("Initial balance cannot be negative");
}
this.owner = owner.trim();
this.balance = balance;
this.frozen = false;
}
// Read-only views of the private data: getters, and no setters
getOwner(): string {
return this.owner;
}
getBalance(): number {
return this.balance;
}
isFrozen(): boolean {
return this.frozen;
}
// The only ways to change the balance, each checking the account's rules first
deposit(amount: number): void {
if (this.frozen) {
throw new Error("Cannot deposit into a frozen account");
}
if (amount <= 0) {
throw new Error("Deposit amount must be positive");
}
this.balance += amount;
console.log(
`Deposited $${amount.toFixed(2)}. New balance: $${this.balance.toFixed(2)}`,
);
}
withdraw(amount: number): void {
if (this.frozen) {
throw new Error("Cannot withdraw from a frozen account");
}
if (amount <= 0) {
throw new Error("Withdrawal amount must be positive");
}
if (amount > this.balance) {
throw new Error(
`Insufficient funds: $${amount.toFixed(2)} > $${this.balance.toFixed(2)}`,
);
}
this.balance -= amount;
console.log(
`Withdrew $${amount.toFixed(2)}. New balance: $${this.balance.toFixed(2)}`,
);
}
freeze(): void {
this.frozen = true;
console.log(`Account for ${this.owner} is now FROZEN.`);
}
}
const account = new BankAccount("Alice", 1000.0);
console.log(`Owner: ${account.getOwner()}`);
console.log(`Balance: $${account.getBalance().toFixed(2)}`);
account.deposit(500.0);
account.withdraw(200.0);
// account.balance = -5000; would not compile: balance is private
// Every attempt to break the rules is refused by the object itself
for (const amount of [-100, 99999]) {
try {
account.withdraw(amount);
} catch (e) {
console.log(`Blocked: ${(e as Error).message}`);
}
}
account.freeze();
try {
account.deposit(100);
} catch (e) {
console.log(`Blocked: ${(e as Error).message}`);
}using System;
using static System.FormattableString;
// A bank account that keeps its data to itself: encapsulation
public class BankAccount
{
// Read-only properties: outside code can read them, only this class can change them
public string Owner { get; }
public double Balance { get; private set; }
public bool IsFrozen { get; private set; }
public BankAccount(string owner, double balance)
{
if (string.IsNullOrWhiteSpace(owner))
{
throw new ArgumentException("Owner name cannot be empty");
}
if (balance < 0)
{
throw new ArgumentException("Initial balance cannot be negative");
}
Owner = owner.Trim();
Balance = balance;
IsFrozen = false;
}
// The only ways to change the balance, each checking the account's rules first
public void Deposit(double amount)
{
if (IsFrozen)
{
throw new InvalidOperationException("Cannot deposit into a frozen account");
}
if (amount <= 0)
{
throw new ArgumentException("Deposit amount must be positive");
}
Balance += amount;
Console.WriteLine(
Invariant($"Deposited ${amount:F2}. New balance: ${Balance:F2}"));
}
public void Withdraw(double amount)
{
if (IsFrozen)
{
throw new InvalidOperationException(
"Cannot withdraw from a frozen account");
}
if (amount <= 0)
{
throw new ArgumentException("Withdrawal amount must be positive");
}
if (amount > Balance)
{
throw new ArgumentException(
Invariant($"Insufficient funds: ${amount:F2} > ${Balance:F2}"));
}
Balance -= amount;
Console.WriteLine(
Invariant($"Withdrew ${amount:F2}. New balance: ${Balance:F2}"));
}
public void Freeze()
{
IsFrozen = true;
Console.WriteLine($"Account for {Owner} is now FROZEN.");
}
}
public static class Program
{
public static void Main()
{
var account = new BankAccount("Alice", 1000.0);
Console.WriteLine($"Owner: {account.Owner}");
Console.WriteLine(Invariant($"Balance: ${account.Balance:F2}"));
account.Deposit(500.0);
account.Withdraw(200.0);
// account.Balance = -5000; would not compile: its setter is private
// Every attempt to break the rules is refused by the object itself
foreach (var amount in new[] { -100.0, 99999.0 })
{
try
{
account.Withdraw(amount);
}
catch (ArgumentException e)
{
Console.WriteLine("Blocked: " + e.Message);
}
}
account.Freeze();
try
{
account.Deposit(100);
}
catch (InvalidOperationException e)
{
Console.WriteLine("Blocked: " + e.Message);
}
}
}package main
import (
"errors"
"fmt"
"strings"
)
// BankAccount keeps its data to itself: encapsulation. Go hides by package, not by
// class: lowercase fields cannot be reached from code in other packages.
type BankAccount struct {
owner string
balance float64
isFrozen bool
}
func NewBankAccount(owner string, balance float64) (*BankAccount, error) {
if strings.TrimSpace(owner) == "" {
return nil, errors.New("Owner name cannot be empty")
}
if balance < 0 {
return nil, errors.New("Initial balance cannot be negative")
}
return &BankAccount{owner: strings.TrimSpace(owner), balance: balance}, nil
}
// Read-only views of the private data: getters, and no setters
func (a *BankAccount) Owner() string { return a.owner }
func (a *BankAccount) Balance() float64 { return a.balance }
func (a *BankAccount) IsFrozen() bool { return a.isFrozen }
// Deposit and Withdraw are the only ways to change the balance, each checking the
// account's rules first
func (a *BankAccount) Deposit(amount float64) error {
if a.isFrozen {
return errors.New("Cannot deposit into a frozen account")
}
if amount <= 0 {
return errors.New("Deposit amount must be positive")
}
a.balance += amount
fmt.Printf("Deposited $%.2f. New balance: $%.2f\n", amount, a.balance)
return nil
}
func (a *BankAccount) Withdraw(amount float64) error {
if a.isFrozen {
return errors.New("Cannot withdraw from a frozen account")
}
if amount <= 0 {
return errors.New("Withdrawal amount must be positive")
}
if amount > a.balance {
return fmt.Errorf("Insufficient funds: $%.2f > $%.2f", amount, a.balance)
}
a.balance -= amount
fmt.Printf("Withdrew $%.2f. New balance: $%.2f\n", amount, a.balance)
return nil
}
func (a *BankAccount) Freeze() {
a.isFrozen = true
fmt.Printf("Account for %s is now FROZEN.\n", a.owner)
}
func main() {
account, err := NewBankAccount("Alice", 1000.0)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Owner: " + account.Owner())
fmt.Printf("Balance: $%.2f\n", account.Balance())
_ = account.Deposit(500.0)
_ = account.Withdraw(200.0)
// account.balance = -5000 would compile here, in the same package; in any other
// package it would not
// Every attempt to break the rules is refused by the object itself
for _, amount := range []float64{-100, 99999} {
if err := account.Withdraw(amount); err != nil {
fmt.Println("Blocked: " + err.Error())
}
}
account.Freeze()
if err := account.Deposit(100); err != nil {
fmt.Println("Blocked: " + err.Error())
}
}It prints:
Owner: Alice
Balance: $1000.00
Deposited $500.00. New balance: $1500.00
Withdrew $200.00. New balance: $1300.00
Blocked: Withdrawal amount must be positive
Blocked: Insufficient funds: $99999.00 > $1300.00
Account for Alice is now FROZEN.
Blocked: Cannot deposit into a frozen account
Look at what the class leaves out and what it keeps:
No setters for owner or balance. There is no set_balance or setBalance. The balance changes only through deposit and withdraw, and both check the account's rules first.
Getters read and never write. Outside code can ask for the owner and the balance, and that is all.
The rules live inside the class. A frozen account, an amount that is not positive, a withdrawal larger than the balance: the object itself refuses each one, so no code that uses it has to remember to.
That is encapsulation at work: the object keeps itself in a valid state for as long as it exists, and the constructor's checks at the start are no longer the only ones.
Watch the Same Attempts on Both
Here are the two accounts side by side, both belonging to Alice with 1000.00, and any code sending both the same attempt. Press withdraw(200.0), withdraw(-100), balance = -99999.0 or owner = "" in any order and watch what each account does with it.

When to Use Getters and Setters
Encapsulation does not mean a getter and a setter for every field. Generating both for everything only adds steps to what is still a public field. Decide field by field:
| Kind of field | Getter | Setter | Why |
|---|---|---|---|
Identity, such as owner or an id | Yes | No | It should not change once the object exists |
A value changed by operations, such as balance | Yes | No | Only deposit and withdraw should change it |
| Details a user may edit, such as a display name | Yes | Yes, with checks | Allow the change, but check it |
Internal state, such as is_frozen | Yes | No | Only its own method, freeze, changes it |
| An implementation detail, such as a cache | No | No | No outside code needs it |
When you do write a setter, make it check the value. A setter that only assigns, such as this.x = x, protects nothing: it is a public field reached through a method.
Common Mistakes
Mistake 1: a getter and a setter for every field. Generated in bulk, they leave every field as open as a public one. Expose only what outside code needs, and prefer methods that carry out an operation, such as deposit and withdraw, to raw setters such as setBalance.
Mistake 2: handing out the object's own list. A getter that returns the private list itself lets the caller change it:
@property
def transactions(self):
return self.__transactions # the private list itselfThe caller can call .append() or .clear() on that list and change the account's private data without any method of the account being asked. Return a copy instead:
@property
def transactions(self):
return list(self.__transactions) # a copy the caller may change freelyMistake 3: hiding so much that the class cannot be used. Encapsulation is not about making everything private and out of reach. It is about a small, clear set of methods that let other code do what it needs while the details stay free to change. If a class is so closed that nobody can use it, it has gone too far.
Key Takeaways
- Encapsulation keeps an object's data private and makes its methods the only way to change it, each method checking the change first, so the object keeps itself valid.
- Java enforces access when the code is compiled, with four levels:
public,protected(its package and subclasses), package access (no modifier) andprivate. Python relies on naming:_nameis a signal, and__nameis renamed but still reachable. - Give a field a getter only when outside code needs it, and a setter only when it may change from outside, always with a check; prefer operations such as
depositto raw setters, and return copies of private lists. - The constructor checks the values an object starts with; encapsulation keeps every later change checked for as long as the object exists.
- Abstraction — Hiding Complexity comes next: showing the users of a class only what they need.