Public vs Private vs Protected vs Default in Java: Key Differences
public members are accessible from anywhere, private members only within their own class, protected members within the same package and subclasses, and default (no modifier) members only within the same package. These access levels control how classes and their members can be accessed to protect data and organize code.Quick Comparison
This table summarizes the visibility of each access modifier in Java.
| Access Modifier | Class | Package | Subclass (same or different package) | World (anywhere) |
|---|---|---|---|---|
| public | Yes | Yes | Yes | Yes |
| private | Yes | No | No | No |
| protected | Yes | Yes | Yes | No |
| default (no modifier) | Yes | Yes | No | No |
Key Differences
public means the member or class is visible everywhere, so any other class can access it regardless of package.
private restricts access strictly to the defining class, hiding details from all other classes even in the same package.
protected allows access within the same package and also to subclasses outside the package, supporting inheritance while limiting general access.
default (no modifier) restricts access to classes within the same package only, providing package-level encapsulation.
Code Comparison
package example; public class AccessDemo { public String publicVar = "Public"; private String privateVar = "Private"; protected String protectedVar = "Protected"; String defaultVar = "Default"; // no modifier public void show() { System.out.println(publicVar); System.out.println(privateVar); System.out.println(protectedVar); System.out.println(defaultVar); } } class Test { public static void main(String[] args) { AccessDemo obj = new AccessDemo(); System.out.println(obj.publicVar); // Accessible // System.out.println(obj.privateVar); // Error: private System.out.println(obj.protectedVar); // Accessible (same package) System.out.println(obj.defaultVar); // Accessible (same package) } }
Subclass Equivalent
package example.sub; import example.AccessDemo; public class SubClass extends AccessDemo { public void testAccess() { System.out.println(publicVar); // Accessible // System.out.println(privateVar); // Error: private System.out.println(protectedVar); // Accessible (subclass) // System.out.println(defaultVar); // Error: default not visible outside package } public static void main(String[] args) { SubClass sub = new SubClass(); sub.testAccess(); } }
When to Use Which
Choose public when you want your class or member to be accessible from anywhere, such as API methods.
Use private to hide internal details and protect data within the class itself.
protected is best when you want to allow subclasses to access members but keep them hidden from unrelated classes.
Use default (no modifier) to share members only within the same package, useful for grouping related classes without exposing them globally.