A public access modifier allows a class member to be accessed by code outside the class. A private access modifier restricts access to the class itself, protecting internal data and implementation details.
How access modifiers work
An access modifier controls the visibility of a class member, such as an attribute, constructor, or method. Code that creates and uses an object is often called client code.
| Access modifier | Where the member can be accessed | Typical use |
|---|---|---|
public | Inside the class and by client code outside it | Constructors and methods that form the class's interface |
private | Only within the class | Attributes and helper methods that should not be directly changed or called externally |
Consider a BankAccount class:
class BankAccount
private balance
public method deposit(amount)
if amount > 0
balance = balance + amount
public method getBalance()
return balance
The balance attribute is private, so client code cannot directly assign an invalid value such as balance = -500. Instead, it must call the public deposit method, which validates the amount before changing the balance.
This supports encapsulation: an object's data and the methods operating on that data are bundled together, while direct access to the internal state is restricted. Public methods provide a controlled interface through which other parts of the program interact with the object.
A common misconception is that a private attribute can never be accessed. It can be accessed and modified by methods within its own class; it is only inaccessible directly from outside that class.
IB exam technique
If asked to distinguish between public and private access, define both modifiers and state the consequence for client code. For an applied question, identify which attributes should be private and explain how public methods protect data integrity through validation. Do not claim that private makes data completely secure; it enforces controlled access within the program's class structure.