Access Modifiers
Overview
Access Modifiers are keywords that set the security boundaries for Classes, Variables, and Methods. They dictate exactly which other files in your project are allowed to interact with your code.
Java has 4 distinct levels of access: 1. Private: The most restrictive. Only code inside the exact same Class file can see it. 2. Default (Package-Private): If you type no keyword at all. It is visible to any class inside the same package (folder). 3. Protected: Visible to anything in the same package, PLUS any Child Subclasses, even if they live in entirely different packages. 4. Public: Completely unrestricted. Any code anywhere in the application (or external APIs) can access it.
Syntax
// Package: com.banking.core
public class Account {
// 1. PUBLIC: Anyone in the world can call this
public String getBankName() { return "Global Bank"; }
// 2. PROTECTED: Only visible in 'com.banking.core' AND subclasses
protected double calculateInterest() { return 5.5; }
// 3. DEFAULT (No keyword): Only visible in 'com.banking.core'
int routingNumber = 12345;
// 4. PRIVATE: ONLY visible inside this exact Account class
private String secretPin = "9999";
}Common Pitfalls
- Assuming 'Default' means 'Public'. In languages like C++, omitting an access modifier defaults to private. In Java, it defaults to Package-Private. If you move a file to a different folder (package) to organize your code, suddenly hundreds of 'default' methods will break because they can no longer see each other.
- Making classes
private. You can make variables and methods private, but a top-level Class cannot be markedprivate. If it were, no one could instantiate it, rendering it useless.
Interview Questions
protected modifier?When building frameworks or parent base classes where you want to provide internal utility methods to developers who extend your class (Subclasses), but you want to keep those methods hidden from random external classes trying to call them directly.
public to private?No. You cannot reduce visibility during inheritance. If the parent promises a method is public, the child must honor that contract. However, you CAN increase visibility (e.g., overriding a protected method and making it public).
Real-World Example
When building an SDK or Library for other developers, you use public for the few API methods you want them to call (like PaymentService.charge()). You use private and default for the thousands of internal helper files (like EncryptionUtils) so the developers don't accidentally mess with the complex internal architecture.
// The single public entry point
public class PaymentGateway {
public void charge(int amount) {
// Hides complex internal network logic
InternalRouter router = new InternalRouter();
router.route(amount);
}
}
// Package-Private class, invisible to the SDK users!
class InternalRouter { ... }Check Your Knowledge
Test your understanding of Access Modifiers with these quick questions.