Access Modifiers
Overview
Access Modifiers are the keywords (`public`, `private`, etc.) that determine exactly who is allowed to talk to your classes, variables, and methods. They are the building blocks of Encapsulation.
Think of a restaurant. The dining area is `public` (anyone can enter). The kitchen is `private` (only staff). By setting boundaries, we prevent chaos.
1. Public (Everyone)
If something is `public`, any file in your entire project can see it and use it.
2. Private (Only Me)
If something is `private`, it can ONLY be seen and used inside the exact Class where it was created. It's totally hidden from the rest of the world.
3. Protected and Default
`protected` means child classes (inheritance) can see it. 'Default' (which means writing no keyword at all) means only files in the exact same folder (package) can see it.
Syntax
A quick summary of how they look in code.
public class SecurityTest {
// ANYONE can touch this
public int publicData = 1;
// Only child classes and same-folder friends can touch this
protected int protectedData = 2;
// Only same-folder friends can touch this (No keyword!)
int defaultData = 3;
// ONLY this exact class can touch this. Maximum security.
private int privateData = 4;
}Common Pitfalls
- Forgetting to write a modifier. If you leave it blank, Java defaults to 'Package-Private', which often causes confusing visibility bugs when working with multiple folders.
Interview Tips
- The golden rule of OOP: Start by making every variable `private`. Only make them `public` if you absolutely, 100% have to.
Real-World Example
Internal helper methods should be hidden from the public API.
public class MathLibrary {
// Public: The user can call this
public double calculateSquareRoot(double number) {
return performComplexMath(number);
}
// Private: The user doesn't need to know how the ugly math works
private double performComplexMath(double num) {
// ... messy logic ...
return result;
}
}