Access Modifiers
IB Syllabus: B3.1 – Use access modifiers to control visibility of class members.
Table of Contents
- Key Concepts
- Worked Examples
- Quick Check
- Spot the Error
- Fill in the Blanks
- Practice Exercises
- Connections
Key Concepts
What are Access Modifiers?
Access modifiers are keywords that control which parts of your program can see and use a class’s attributes and methods. They are the mechanism that makes encapsulation possible – without them, any code could access any data.
Java has three access modifiers you need to know:
| Modifier | Who can access? | Use for |
|---|---|---|
private | Only code inside the same class | Attributes (almost always), helper methods |
public | Code in any class | Constructors, getters, setters, API methods |
protected | Code in the same class and its subclasses | Attributes or methods that subclasses need but outside code should not touch |
There is also a fourth level – default (no keyword) – which allows access from any class in the same package. IB does not assess this, but you may encounter it in real Java code.
The Standard Rules
For IB and professional Java development, follow these rules:
Attributes: almost always private
private String name;
private double balance;
private int age;
Making attributes private ensures no external code can read or modify them without going through your methods. This is the foundation of encapsulation.
Constructors and public methods: public
public BankAccount(String owner, double balance) { ... }
public double getBalance() { ... }
public void deposit(double amount) { ... }
These form the class’s public interface – the way other classes interact with your objects.
Helper methods: private
private boolean isValidAmount(double amount) {
return amount > 0;
}
Helper methods are internal tools that support public methods. They are implementation details that other classes should not call directly.
An access modifier (also called an access specifier) determines the visibility of a class member.
privatemeans the member is only accessible within the class itself. This is the precise definition IB mark schemes expect.
Why Not Make Everything Public?
If everything is public, any code anywhere can:
// With public fields -- dangerous
account.balance = -999999; // no validation
account.owner = ""; // empty name
account.balance = account.balance * 1000; // arbitrary modification
With private fields and public methods:
// With private fields -- safe
account.deposit(-999999); // rejected by validation
account.setOwner(""); // rejected by validation
// account.balance = ... // compile error -- cannot access private field
The compiler itself enforces the protection. A private field cannot be accessed from outside the class – it is not a suggestion, it is a hard rule enforced at compile time.
protected – For Inheritance
protected sits between private and public. A protected member is accessible within the class itself AND within any class that extends it (subclasses), but not from unrelated classes.
public class Animal {
protected String name; // subclasses can access directly
private int internalId; // only Animal can access
public Animal(String name) {
this.name = name;
}
}
public class Dog extends Animal {
public Dog(String name) {
super(name);
System.out.println(this.name); // OK -- protected, Dog is a subclass
// System.out.println(this.internalId); // ERROR -- private, even subclasses can't access
}
}
Use
protectedsparingly. In most cases,privatewith apublicgetter is better because it gives the parent class full control over how the data is accessed.protectedgives subclasses direct access, which can lead to tight coupling.
Access Modifier Summary Diagram
Same class Subclass Other classes
private ──► ✓ ✗ ✗
protected ──► ✓ ✓ ✗
public ──► ✓ ✓ ✓
Common Mistakes
Mistake 1: Making attributes public out of laziness
public int age; // BAD -- no validation, no control
Fix: private int age; with a validated setter.
Mistake 2: Making everything private including methods other classes need
private double getBalance() { ... } // BAD -- other classes can't read the balance
Fix: getters and setters should be public.
Mistake 3: Confusing private and protected
private means ONLY the same class. protected means the same class AND subclasses. If a subclass needs direct access to a parent’s field, use protected – but prefer private with a getter when possible.
Worked Examples
Example 1: Choosing the Right Modifier
For each member, decide the appropriate access modifier and explain why:
| Class | Member | Modifier | Why |
|---|---|---|---|
Student | name (attribute) | private | Data should be hidden; accessed via getter |
Student | getName() | public | Other classes need to read the name |
Student | setGrade(int) | public | Other classes need to modify the grade (with validation) |
Student | validateGrade(int) | private | Internal helper; no reason for external code to call this directly |
Animal | sound (attribute used by Dog, Cat subclasses) | protected | Subclasses need direct access; external classes do not |
BankAccount | BankAccount(String, double) | public | Other classes need to create BankAccount objects |
Example 2: Compile Error Analysis
public class Secret {
private int code = 42;
public int getCode() { return code; }
}
public class Main {
public static void main(String[] args) {
Secret s = new Secret();
System.out.println(s.code); // LINE A
System.out.println(s.getCode()); // LINE B
}
}
Line A: Compile error – code is private, cannot be accessed from Main.
Line B: Works – getCode() is public, returns the value of the private field.
This is encapsulation in action: the data is hidden, but a controlled access point (the getter) is provided.
Quick Check
Q1. What does the private access modifier mean?
Q2. What is the standard access modifier pattern for a well-designed class?
Q3. A protected attribute in a parent class can be accessed by:
Q4. What happens if you try to access a private field from another class?
Spot the Error
This class works but has a design flaw -- one member has the wrong access modifier. Click the line with the issue, then pick the fix.
Pick the fix:
Fill in the Blanks
Complete the access modifier rules:
Access Levels (most restrictive to least)
==========================================
= only within the same class
= same class + subclasses
= any class can access
Standard Pattern
================
Attributes:
Getters/Setters:
Helper methods: Practice Exercises
Core
- Modifier audit – For each member below, state whether it should be
private,protected, orpublic, and explain why:BankAccount.balanceBankAccount.getBalance()BankAccount.calculateInterest()(used only byaddInterest())Vehicle.speed(needed by Car and Motorcycle subclasses)
- Fix the class – This class has three access modifier problems. Find and fix them:
public class Employee { private String name; public double salary; private String getName() { return name; } public boolean isValidSalary(double s) { return s >= 0; } }
Extension
- Design from scratch – Design a
Patientclass for a hospital system. Decide which members areprivate,public, orprotected. Justify each choice. Include at least one helper method that should be private.
Challenge
- Access control analysis – Given classes
Animal(parent),Dog(child), andMain(unrelated), draw a table showing which members ofAnimaleach class can access, for each access level (private,protected,public). Give a specific example of when you would use each level.
Connections
- Prerequisites: Encapsulation – access modifiers are the tool that implements encapsulation
- Next: Static Members –
staticis not an access modifier but is often confused with them - Forward: Inheritance –
protectedbecomes important when subclasses need parent data