Introduction
In Java, writing code is not just about making it work β it is about making it secure, structured, and maintainable β
Imagine a situation where every variable in your program is accessible from anywhere.
Anyone can modify it. Any part of the code can misuse it.
That would quickly lead to:
- β Data corruption
- β Unexpected bugs
- β Security issues
- β Difficult debugging
To prevent this, Java provides Access Modifiers π
Access modifiers control where a class, variable, method, or constructor can be accessed from.
This article explains all four access modifiers in detail with clear examples, practical programs, common confusions, and mistakes to avoid.
π§ What Are Access Modifiers?
Access modifiers define the visibility scope of:
- Variables
- Methods
- Constructors
- Classes
Java provides four access levels:
1οΈβ£ private
2οΈβ£ Default (no keyword)
3οΈβ£ protected
4οΈβ£ public
π Access Modifier Comparison Table
| Modifier | Same Class | Same Package | Subclass (Other Package) | Outside Package |
|---|---|---|---|---|
| private | β | β | β | β |
| default | β | β | β | β |
| protected | β | β | β | β |
| public | β | β | β | β |
This table is extremely important for exams and interviews π―
π 1οΈβ£ Private Access Modifier
πΉ Definition
private members are accessible only within the same class.
πΉ Purpose
Used for data hiding and encapsulation.
βΆοΈ Example 1: Private Variable
class Student {
private int rollNo;
public void setRollNo(int r) {
rollNo = r;
}
public void display() {
System.out.println("Roll No: " + rollNo);
}
}
public class PrivateDemo {
public static void main(String[] args) {
Student s = new Student();
s.setRollNo(101);
s.display();
}
}
π§ Step-by-Step Explanation
rollNois private β cannot be accessed outside classsetRollNo()allows controlled modificationdisplay()prints value- Object interacts through public methods
β Common Mistake
s.rollNo = 101; // β Compilation Error
Why?
Because rollNo is private and cannot be accessed outside the class.
π― When to Use Private?
- Always for instance variables
- When you want controlled access
- To protect sensitive data
π¦ 2οΈβ£ Default Access Modifier (Package-Private)
If no modifier is specified β it becomes default access.
Accessible only within the same package.
βΆοΈ Example 2: Default Access
class Test {
int value = 50; // default access
void show() {
System.out.println("Value: " + value);
}
}
public class DefaultDemo {
public static void main(String[] args) {
Test t = new Test();
t.show();
}
}
π§ Explanation
valuehas default access- Accessible within same package
- Not accessible outside package
β Common Confusion
Is default same as private?
β No
Default β package-level access
Private β class-level access
πΏ 3οΈβ£ Protected Access Modifier
protected members are accessible:
- Within same class
- Within same package
- In subclasses (even in different package)
Used mainly when inheritance is involved.
βΆοΈ Example 3: Protected Member
class Person {
protected String name = "Ajay";
protected void showName() {
System.out.println("Name: " + name);
}
}
public class ProtectedDemo {
public static void main(String[] args) {
Person p = new Person();
p.showName();
}
}
π§ Explanation
nameandshowName()are protected- Accessible inside same package
- Also accessible in subclasses
β Why Use Protected?
When designing for inheritance:
- Allow subclass access
- Restrict public exposure
π 4οΈβ£ Public Access Modifier
public members are accessible from anywhere.
Most open access level.
βΆοΈ Example 4: Public Access
class Demo {
public int number = 100;
public void display() {
System.out.println("Number: " + number);
}
}
public class PublicDemo {
public static void main(String[] args) {
Demo d = new Demo();
d.display();
}
}
π§ Explanation
numberaccessible everywheredisplay()accessible everywhere- No restrictions
β οΈ Warning
Making everything public is bad design β
It breaks encapsulation and security.
π Access Modifiers for Classes
Top-level classes can only be:
public- default
They cannot be:
privateprotected
βΆοΈ Example
public class MyClass {
}
Valid.
private class MyClass {
}
β Invalid.
β Common Confusions
β Why are variables usually private?
To:
- Prevent direct modification
- Force controlled access
- Maintain object integrity
β Can private methods be accessed in another class?
β No
β Can protected members be accessed without inheritance?
Yes, within same package.
β What happens if no modifier is written?
Default access applies.
β Common Mistakes
β Making all variables public
Bad practice.
β Confusing default with private
Default β private.
β Forgetting encapsulation
public int balance; // β unsafe
β Trying to access private members outside class
Compilation error.
π§ͺ Tricky Scenario
class Test {
private int x = 10;
void show() {
System.out.println(x);
}
}
public class TrickyDemo {
public static void main(String[] args) {
Test t = new Test();
t.show();
}
}
π§ Why does this work?
Because show() is inside the class and can access private member.
Package Example:-
π¦ SAME PACKAGE EXAMPLES (Very Important Section)
To properly understand access modifiers, letβs simulate a same package scenario.
Assume both classes are in:
package mypackage;
π 1οΈβ£ Private Access Modifier
Private members are accessible only inside the same class.
βΆοΈ Example: Private (Same Package)
File: Student.java
package mypackage;
class Student {
private int rollNo = 101;
void show() {
System.out.println("Roll No: " + rollNo);
}
}
File: MainClass.java
package mypackage;
public class MainClass {
public static void main(String[] args) {
Student s = new Student();
s.show(); // β
Allowed
// System.out.println(s.rollNo); β Not Allowed
}
}
π§ Explanation
rollNois private- It can only be accessed inside
Studentclass - Even though
MainClassis in same package, it CANNOT access private members
π Private = Class-level access only
π¦ 2οΈβ£ Default Access Modifier (Package-Private)
If no modifier is written β default access.
Accessible inside the same package only.
βΆοΈ Example: Default Access (Same Package)
File: Employee.java
package mypackage;
class Employee {
int id = 1; // default access
void display() {
System.out.println("Employee ID: " + id);
}
}
File: MainClass.java
package mypackage;
public class MainClass {
public static void main(String[] args) {
Employee e = new Employee();
System.out.println(e.id); // β
Allowed
e.display(); // β
Allowed
}
}
π§ Explanation
idhas default access- Both classes are in same package
- So access is allowed
π Default = Package-level access
πΏ 3οΈβ£ Protected Access Modifier
Protected members are accessible:
- Inside same class
- Inside same package
- In subclass (even outside package)
βΆοΈ Example: Protected (Same Package)
File: Person.java
package mypackage;
class Person {
protected String name = "Ajay";
protected void showName() {
System.out.println("Name: " + name);
}
}
File: MainClass.java
package mypackage;
public class MainClass {
public static void main(String[] args) {
Person p = new Person();
System.out.println(p.name); // β
Allowed
p.showName(); // β
Allowed
}
}
π§ Explanation
- Protected behaves like default inside same package
- Accessible normally
π Inside same package β protected = default behavior
π 4οΈβ£ Public Access Modifier
Public members are accessible everywhere.
βΆοΈ Example: Public (Same Package)
File: Demo.java
package mypackage;
public class Demo {
public int value = 100;
public void show() {
System.out.println("Value: " + value);
}
}
File: MainClass.java
package mypackage;
public class MainClass {
public static void main(String[] args) {
Demo d = new Demo();
System.out.println(d.value); // β
Allowed
d.show(); // β
Allowed
}
}
π Important Clarification
Inside the same package:
- default β accessible
- protected β accessible
- public β accessible
- private β NOT accessible
π― Best Practice Guidelines
β Always make instance variables private
β Provide public getter/setter when needed
β Use protected carefully
β Avoid unnecessary public exposure
β Use default access for package-internal logic
π Summary Table
| Modifier | Best Use Case |
|---|---|
| private | Data hiding |
| default | Package-level grouping |
| protected | Inheritance support |
| public | Open API exposure |
β Conclusion
Access modifiers are the backbone of secure and maintainable Java programming π
By properly using:
privatefor data hidingdefaultfor package controlprotectedfor inheritance designpublicfor controlled exposure
You create Java applications that are:
- Secure π
- Organized π¦
- Maintainable π οΈ
- Professionally structured π
Mastering access modifiers is essential for writing high-quality Java code and for excelling in interviews and real-world development.