In the Encapsulation chapter we said that an object should guard its own data and expose only a safe set of operations. But saying "please don't touch my balance" is not enough. The language needs a way to enforce it. That is the job of access modifiers.
An access modifier is a keyword that controls from where in the program a class, field, method or constructor can be used. It is checked by the compiler (or, in Python, followed by convention).
Think of an office building. The lobby is open to everyone (public). Your floor is open to colleagues in your department (package). Some meeting rooms are also open to trainees from your department working at other branches (protected). Your personal locker is yours alone (private).
In this chapter we cover Java's four access levels in depth, including the famously tricky protected, then compare with C++ and Python.
Why Restrict Access at All?
Beginners sometimes think access modifiers are about security against hackers. They are not: anyone with your source code or a debugger can read memory. Access modifiers protect programmers from mistakes and protect your design from becoming impossible to change.
Invariants stay true. If
balancecan only change throughdeposit()andwithdraw(), and those methods reject negative amounts, then the balance can never be corrupted by some far-away line of code.Freedom to change. Anything private can be renamed, removed or re-implemented without breaking other classes. Anything public is a promise you must keep.
Smaller mental load. A reader of your class only needs to understand its public part to use it.
The golden rule follows directly: give every member the most restrictive access that still works. Open it up later only when there is a real need.
Java's Four Access Levels
Java has three keywords but four levels. Writing no keyword at all gives the fourth level, called default or package-private access.
Modifier | Same class | Same package | Subclass in another package | Any other class |
|---|---|---|---|---|
| ✓ | ✗ | ✗ | ✗ |
(none) package-private | ✓ | ✓ | ✗ | ✗ |
| ✓ | ✓ | ✓ (with a rule, see below) | ✗ |
| ✓ | ✓ | ✓ | ✓ |
So from most to least restrictive:
private < package-private < protected < public
(class) (package) (package + subclasses) (everyone)A very common exam slip: in Java, protected is wider than package-private, not narrower. A protected member is visible to the whole package and to subclasses elsewhere.
A Complete Example Across Two Packages
Access levels only become visible when code lives in different packages. Here is a small banking project:
src/
├── com/bank/
│ ├── Account.java (the class we protect)
│ └── Auditor.java (same package)
└── com/app/
├── SavingsAccount.java (subclass, different package)
└── Main.java (unrelated class, different package) package com.bank;
public class Account {
private double balance; // only code inside Account
String branchCode = "BLR01"; // package-private: only com.bank
protected String holder; // com.bank + subclasses anywhere
public final String number; // everyone
public Account(String number, String holder, double opening) {
this.number = number;
this.holder = holder;
this.balance = opening;
}
public void deposit(double amt) {
if (amt <= 0) throw new IllegalArgumentException("Deposit must be positive");
balance += amt;
}
public double getBalance() { return balance; }
protected void addInterest(double rate) { balance += balance * rate; }
// private is per CLASS, not per object: we may read other.balance here
public boolean hasMoreThan(Account other) {
return this.balance > other.balance;
}
} package com.bank;
public class Auditor { // same package as Account
public static void inspect(Account a) {
System.out.println("Branch : " + a.branchCode); // package-private: OK
System.out.println("Holder : " + a.holder); // protected: OK (same package)
// System.out.println(a.balance); // private: compile error
System.out.println("Balance: " + a.getBalance());
}
} package com.app;
import com.bank.Account;
public class SavingsAccount extends Account { // different package, subclass
public SavingsAccount(String number, String holder, double opening) {
super(number, holder, opening);
}
public void monthEnd() {
addInterest(0.01); // protected, inherited: OK
System.out.println("Interest added for " + holder); // protected field: OK
// System.out.println(branchCode); // package-private: compile error
}
} package com.app;
import com.bank.Account;
import com.bank.Auditor;
public class Main {
public static void main(String[] args) {
SavingsAccount s = new SavingsAccount("SB-1001", "Meera", 10000);
s.deposit(2000); // public
s.monthEnd();
System.out.println(s.number + " balance = " + s.getBalance());
Account c = new Account("CA-2002", "Kabir", 5000);
System.out.println("Meera richer than Kabir? " + s.hasMoreThan(c));
Auditor.inspect(s);
}
}Compile and run from the src folder:
javac -d out com/bank/*.java com/app/*.java
java -cp out com.app.MainOutput:
Interest added for Meera
SB-1001 balance = 12120.0
Meera richer than Kabir? true
Branch : BLR01
Holder : Meera
Balance: 12120.0Check each access against the table:
Where | Accesses | Allowed? | Why |
|---|---|---|---|
|
| ✓ |
|
|
| ✓ | same package (package-private and protected both include the package) |
|
| ✗ | private to |
|
| ✓ | protected, used through inheritance |
|
| ✗ | package-private and we are in |
|
| ✓ | public |
Private is per class, not per object
Notice hasMoreThan(Account other) reads other.balance directly, even though other is a different object. That is legal. Access control in Java (and C++) asks "which class's code is running?", not "which object is being touched?". This is why equals() and compareTo() methods can compare private fields of two objects.
The Tricky Rule of protected
Outside its package, a subclass can use an inherited protected member only through references of its own type (or its subclasses), which includes plain this. It cannot reach into an arbitrary Account object.
The reason: if any subclass could read holder on any Account, then a stranger could write a tiny subclass just to snoop on other people's accounts. The rule limits a subclass to objects that are part of its own family.
package com.app;
import com.bank.Account;
public class Snoop extends Account {
public Snoop() { super("X", "Y", 0); }
void test(Account other, Snoop same) {
System.out.println(holder); // OK: inherited through this
System.out.println(same.holder); // OK: reference of type Snoop
System.out.println(other.holder); // error: protected via an Account reference
System.out.println(other.balance); // error: private
System.out.println(other.branchCode);// error: package-private
}
}Compiler output:
com\app\Snoop.java:11: error: holder has protected access in Account
System.out.println(other.holder); // error: protected via an Account reference
^
com\app\Snoop.java:12: error: balance has private access in Account
System.out.println(other.balance); // error: private
^
com\app\Snoop.java:13: error: branchCode is not public in Account; cannot be accessed from outside package
System.out.println(other.branchCode);// error: package-private
^
3 errorsThe first two lines compile; the last three do not. The error messages even tell you which level blocked you.
Access Modifiers on Classes, Constructors and Overrides
Top-level classes
A top-level class can be only public or package-private. private or protected top-level classes are compile errors (they make sense only for nested classes). A source file may contain at most one public top-level class, and the file name must match it.
Private constructors
Making a constructor private stops other classes from writing new. This is used for utility classes such as java.lang.Math (which should never be instantiated) and for patterns that control object creation, which you will meet in Creational Patterns: Singleton, Factory & Builder.
Overriding cannot reduce visibility
When you override a method, the new method must be at least as accessible as the original. A public method must stay public; a protected method may stay protected or become public.
class Base {
protected void show() { }
}
class Child extends Base {
@Override
void show() { } // error: attempting to assign weaker access privileges; was protected
}Why? Because of substitutability. Code holding a Base reference is allowed to call show(). If the actual object were a Child that hid show(), that promise would be broken. (We will see this principle in full in SOLID: Liskov Substitution Principle.) Private methods are not inherited at all, so a same-named method in the child is a brand-new method, not an override.
A note on Java modules
Since Java 9, the module system adds one more layer above packages: a public class in a package that its module does not export is still not usable from other modules. For ordinary programs on the classpath (like ours), this does not apply.
Access Control in C++
C++ has public, protected and private, but they work as sections of a class rather than per-member keywords, and there is no package level.
Members of a
classare private by default; members of astructare public by default. The same goes for the default inheritance mode, and these defaults are the only difference between the two keywords.protectedin C++ means "this class and derived classes" only. It does not include any package-like group, so it is narrower than Java'sprotected.A friend function or class is explicitly granted access to private members.
Inheritance itself has an access mode:
public,protectedorprivateinheritance.
#include <iostream>
#include <string>
#include <utility>
class Account {
private:
double balance = 0; // only Account (and its friends)
protected:
std::string holder; // Account + derived classes
public:
explicit Account(std::string h) : holder(std::move(h)) {}
void deposit(double amt) { if (amt > 0) balance += amt; }
friend void audit(const Account& a); // a friend function may see private members
};
void audit(const Account& a) {
std::cout << "Audit: " << a.holder << " has " << a.balance << '\n';
}
class Savings : public Account { // public inheritance: public stays public
public:
using Account::Account;
void greet() const { std::cout << "Hello, " << holder << '\n'; } // protected: OK
// void peek() const { std::cout << balance; } // error: 'balance' is private
};
class Locked : private Account { // private inheritance: everything inherited becomes private
public:
Locked() : Account("Locked") {}
void add(double x) { deposit(x); } // usable inside Locked...
};
int main() {
Savings s("Meera");
s.deposit(500);
s.greet();
audit(s);
Locked l;
l.add(100);
// l.deposit(100); // error: deposit is inaccessible here
}Output:
Hello, Meera
Audit: Meera has 500If we try to touch the private balance from main, or call deposit on a privately inherited object, g++ reports:
bad.cpp:10:7: error: ‘double Account::balance’ is private within this context
bad.cpp:12:14: error: ‘void Account::deposit(double)’ is inaccessible within this context
bad.cpp:12:14: error: ‘Account’ is not an accessible base of ‘Locked’Inheritance modes in C++
The mode caps the access of inherited members (private members of the base are never accessible in the derived class, whatever the mode):
Member in base |
|
|
|
|---|---|---|---|
| public | protected | private |
| protected | protected | private |
| not accessible | not accessible | not accessible |
Only public inheritance models an "is-a" relationship. Private inheritance means "implemented in terms of" and is usually better written as composition (see Association, Aggregation & Composition). The default mode is private for class and public for struct.
Access "Control" in Python
Python has no access keywords. It relies on naming conventions, summed up as "we are all consenting adults here":
name: public._name: internal by convention. Nothing stops access, but tools and readers treat it as "do not use from outside".from module import *skips such names.__name(two leading underscores, at most one trailing): name mangling. Inside classAccountit is renamed to_Account__name. The goal is to avoid accidental clashes with subclasses, not real privacy.
class Account:
def __init__(self, holder, balance):
self.holder = holder # public
self._branch = "BLR01" # "internal": a convention only
self.__balance = balance # name-mangled to _Account__balance
def balance(self):
return self.__balance
a = Account("Meera", 1000)
print(a.holder, a._branch, a.balance())
try:
print(a.__balance)
except AttributeError as e:
print("AttributeError:", e)
print(a._Account__balance) # still reachable: Python does not truly hide itOutput:
Meera BLR01 1000
AttributeError: 'Account' object has no attribute '__balance'
1000Java vs C++ vs Python at a Glance
Point | Java | C++ | Python |
|---|---|---|---|
Levels | private, package-private, protected, public | private, protected, public (+ friend) | convention only: |
Default when nothing written | package-private | private ( | public |
Meaning of protected | package + subclasses | class + derived classes | no such keyword |
Enforced by | compiler (and JVM) | compiler | nobody; name mangling only renames |
Granting special access | put the classes in one package |
| not needed |
Choosing the Right Modifier
Fields:
private, almost always. Expose behaviour (methods), not raw data. Constants (public static final) are the usual exception.Helper methods:
private. If other classes in the same package need them, package-private.Hooks meant for subclasses:
protected, and only when you have truly designed the class for extension. A protected member is part of your public contract for every future subclass.The operations users need:
public, and keep this list short.
Common Mistakes
Thinking
protectedis narrower than default in Java. It is wider: package plus subclasses.Thinking "default" means public. No modifier in Java means package-private. (Interface methods are the exception: they are implicitly public.)
Making fields protected "for convenience". Every subclass can now break your invariants. Prefer private fields with protected methods if subclasses need controlled access.
Expecting a subclass in another package to read a protected field on any parent object. Only through
thisor references of the subclass's own type.Public getters and setters for everything. A setter for every field is barely better than a public field. Expose meaningful operations like
deposit().Believing Python's
__xis truly private. It is only renamed to_ClassName__x.
Interview and GATE-Style Questions
Q1. Arrange Java's access levels from most to least restrictive.
private → package-private (default) → protected → public.
Q2. Can a method of class A access a private field of another object of class A?
A access a private field of another object of class A?Yes. Access is checked per class, not per object. This is what makes equals(Object o) implementations able to compare private fields.
Q3. A subclass B in package p2 extends A in package p1. A has protected int x. Inside B, which compile: x, this.x, new A().x, new B().x?
B in package p2 extends A in package p1. A has protected int x. Inside B, which compile: x, this.x, new A().x, new B().x?x, this.x and new B().x compile. new A().x does not, because outside the package a protected member can be accessed only through a reference of type B or a subclass of B.
Q4. A parent method is protected. Which access levels can the overriding method have?
protected. Which access levels can the overriding method have?protected or public. Reducing it to package-private or private is a compile error ("attempting to assign weaker access privileges").
Q5. Can a top-level Java class be private? Can a nested class?
A top-level class can be only public or package-private. A nested (member) class can use any of the four levels.
Q6. What is the difference between class and struct in C++?
class and struct in C++?Only the defaults: in a class, members and base classes are private by default; in a struct they are public by default. Both can have methods, constructors, inheritance and virtual functions.
Q7. With class D : protected B in C++, what is the access of B's public members inside D?
class D : protected B in C++, what is the access of B's public members inside D?They become protected in D: usable in D and classes derived from D, but not from outside code through a D object.
Summary
Access modifiers enforce encapsulation: they decide where a member can be used.
Java:
private(class) < package-private (package) <protected(package + subclasses) <public(everyone).Private access is per class, not per object.
Outside the package, protected members are reachable only through the subclass's own type.
Overrides may widen access but never narrow it.
C++:
classdefaults to private,structto public;friendgrants access; inheritance mode caps inherited access.Python: no enforcement;
_xis a convention,__xtriggers name mangling.
Start private. Every step toward public is a promise you will have to keep.