← Back to Chapters

Java Access Modifiers

? Java Access Modifiers

? Quick Overview

Access modifiers in Java control the visibility and accessibility of classes, methods, variables, and constructors. They help enforce encapsulation and protect data from unauthorized access.

? Key Concepts

  • public – accessible from anywhere
  • protected – accessible within same package or subclasses
  • default (no keyword) – accessible within same package
  • private – accessible only within the same class

? Syntax / Theory

Access modifiers are written before the class, method, or variable declaration. Only public and default are allowed for top-level classes.

? Code Example(s)

? View Code Example
// Demonstrates all four access modifiers in Java
public class AccessDemo {

public int publicVar = 10;

protected int protectedVar = 20;

int defaultVar = 30;

private int privateVar = 40;

public void showValues() {
System.out.println(publicVar);
System.out.println(protectedVar);
System.out.println(defaultVar);
System.out.println(privateVar);
}
}

? Live Output / Explanation

Explanation

All variables are accessible inside the same class. However, when accessed from another class or package, visibility depends on the access modifier used.

? Interactive Visibility Simulator

Click a Scenario to see which modifiers grant access from that location:

public
✅ Allowed
protected
✅ Allowed
default
✅ Allowed
private
✅ Allowed

Current Context: Inside the class where variable is declared.

✅ Tips & Best Practices

  • Use private variables and provide access via methods
  • Prefer default or protected for internal APIs
  • Use public only when necessary
  • Follow encapsulation to improve maintainability

? Try It Yourself

  • Create two classes in the same package and test access
  • Create a subclass in another package and test protected
  • Try accessing private members from outside the class