What Are Access Modifiers in Java: Explanation and Examples
access modifiers are keywords that set the visibility of classes, methods, and variables. They control where these elements can be accessed from, helping to protect data and organize code. The main modifiers are public, private, protected, and default (no modifier).How It Works
Think of access modifiers like the doors and windows of a house. They decide who can enter or see inside. In Java, these modifiers control which parts of your code can be used by other parts.
Public means the door is wide open for everyone. Any other class anywhere can use it. Private is like a locked room only the owner can enter. No one else can see or use it. Protected is a bit like a family-only room, accessible to related classes (in the same package or subclasses). The default (no modifier) is like a room open only to neighbors in the same package.
This system helps keep your code safe and organized by hiding details that shouldn’t be changed or seen outside their intended area.
Example
This example shows how different access modifiers affect visibility of class members.
package example; public class AccessExample { public int publicVar = 1; // Visible everywhere private int privateVar = 2; // Visible only inside this class protected int protectedVar = 3; // Visible in package and subclasses int defaultVar = 4; // Visible in package only public void printVars() { System.out.println("Public: " + publicVar); System.out.println("Private: " + privateVar); System.out.println("Protected: " + protectedVar); System.out.println("Default: " + defaultVar); } } class TestAccess { public static void main(String[] args) { AccessExample example = new AccessExample(); System.out.println(example.publicVar); // Works // System.out.println(example.privateVar); // Error: private System.out.println(example.protectedVar); // Works (same package) System.out.println(example.defaultVar); // Works (same package) example.printVars(); // Can access all inside class } }
When to Use
Use access modifiers to protect your code and make it easier to maintain. Mark variables or methods private when they should only be used inside their own class, like secret ingredients in a recipe. Use public for things you want others to use freely, like a menu in a restaurant.
Protected is useful when you want to share with related classes but keep outsiders away, like family-only access. Default access is good for grouping related classes in the same package.
By carefully choosing access levels, you prevent accidental changes and keep your program safe and clear.
Key Points
- Public: accessible from anywhere.
- Private: accessible only within the class.
- Protected: accessible within package and subclasses.
- Default (no modifier): accessible only within the package.
- Access modifiers help encapsulate and protect data.