Skip to content
BENIBIX Learn

Access Modifier

Development🧭 Programming ParadigmsObject-Oriented Programming

Also known as Access Modifiers, Public and Private, Visibility Modifier

A word like public or private that says which code may use a part.

Think of it like

It is like a shop with a front room and a staff-only room. Shoppers can only go in the front.

Example

A BankAccount class keeps balance private. Other code must call deposit(), which checks the amount first.

Why it matters

It lets a class guard its own data. Other code cannot reach in and break the rules.

Definition

An access modifier is a word that says which code may use a part of a class. public means any code can use it. private means only the class itself can. Java and C# also have protected, for the class and its child classes. Python has no enforced private, so a leading underscore, like _age, asks others to keep out.

Example code

java
public class BankAccount {
    private int balance;
    public void deposit(int amount) {
        if (amount > 0) balance += amount;
    }
}
The balance is private. The only way to change it is the public deposit method.
name is public and age is private. Only the Dog class may touch age.

Common mistake

Making everything public to save time. Later, any code can change data the class relied on.

Key takeaways

  1. 1
    public. Any code may use it.
  2. 2
    private. Only the class itself may use it.
  3. 3
    Guards the rules. Data changes only through methods.