Access Modifiers
Access modifiers control who can see or use a class, method, or field from other parts of a program. Java provides four levels: public, private, protected, and default (no keyword at all, also called package-private).
1. What are Access Modifiers?
Access modifiers control who can see or use a class, method, or field from other parts of a program. Java provides four levels: public, private, protected, and default (no keyword at all, also called package-private).
2. Why is it used?
They let you control exactly how much of your class's internal details should be exposed to the outside world, supporting proper encapsulation and preventing unwanted or unsafe access from other parts of a large codebase.
3. Real-Life Example
Think of different areas in a company building — the reception area is open to everyone (public), certain floors are open only to employees of that department (protected or default), and the server room is accessible only to specific authorized staff (private).
4. Syntax
javapublic class ClassName { } private dataType fieldName; protected returnType methodName() { } dataType fieldName; // default (package-private) - no keyword
5. Example Program
javaclass BankAccount { private double balance = 1000; public double getBalance() { return balance; } } public class AccessModifierDemo { public static void main(String[] args) { BankAccount acc = new BankAccount(); System.out.println("Balance: " + acc.getBalance()); } }
Output:
Balance: 1000.06. Key Points to Remember
private: accessible only within the same class.- Default (no modifier): accessible within the same package only.
protected: accessible within the same package, and also by subclasses in other packages.public: accessible from anywhere in the program.