java
- IntroductionInstallation and SetupJava Syntax and StructureRunning Your First ProgramJava VariablesData Types in JavaOperators in JavaJava Input and OutputControl StatementsLoops in JavaMethods in Java (Functions)Arrays in JavaString Handling in JavaOOPS Concept in JavaClasses and ObjectsConstructor and Constructor Overloadingthis KeywordStatic MembersInheritanceAggregation in JavaMethod OverloadingMethod Overridingsuper KeywordFinal Keyword with Class, Method, and VariablesAccess Modifiers in javaEncapsulation in Java Polymorphism in JavaAbstraction in JavaAbstract ClassesInterfaces in JavaDifference between Abstract Class and Interface Nested and Inner Classes Exception HandlingJava PackagesWrapper Classes and AutoboxingJava Collections FrameworkFile Handling in JavaMultithreadingBasics of Java Memory Management and Garbage CollectionJava JDBC
Access Modifiers in Java – Complete Tutorial
Last Updated on: 17th Nov 2025 13:01:08 PM
Welcome to this beginner-friendly tutorial on Access Modifiers in Java! Access modifiers control who can access your class members (fields, methods, constructors). They are essential for encapsulation, security, and code organization.
This tutorial uses a real-world project-based example — an Employee Management System — to show how access modifiers are used in production software.
What Are Access Modifiers?
In Java, Access Modifiers are keywords that define how much access (visibility) a class, variable, method, or constructor has.They define visibility from other classes.
They control where a member can be accessed — inside the class, within the package, or outside the package.
Java provides 4 types of Access Modifiers:
-
public
-
private
-
protected
-
default (no keyword)
1. public Access Modifier
Accessible from anywhere — within the class, outside the class, outside the package, or from any project.
Purpose:
-
For APIs, main classes, shared utilities
-
Full visibility
Example:
public class Student {
public String name = "Amit";
public void showName() {
System.out.println("Name: " + name);
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.showName(); // Accessible everywhere
}
}
Use public when you want your method/class to be available to all.
2. private Access Modifier
Accessible only inside the same class.Not accessible outside the class — not even by subclasses.
Purpose:
-
Hide internal data
-
Enforce encapsulation
-
Prevent direct modification
Example:
class Account {
private double balance = 5000;
private void showBalance() {
System.out.println("Balance: " + balance);
}
public void accessBalance() {
showBalance(); // Allowed
}
}
public class Main {
public static void main(String[] args) {
Account a = new Account();
// a.balance; // ❌ Not allowed
// a.showBalance();// ❌ Not allowed
a.accessBalance(); // ✔ Allowed
}
}
Use private for sensitive data like password, balance, OTP, salary, etc.
3. protected Access Modifier
Accessible:
-
inside the same class
-
inside the same package
-
outside the package but only via inheritance
Purpose:
-
Allow inheritance while hiding from outsiders
-
Share data with subclasses
Example: Base Employee with Protected Fields
// BaseEmployee.java
public class BaseEmployee {
protected String department;
protected int yearsOfService;
protected void promote() {
yearsOfService++;
System.out.println("Promoted! Years: " + yearsOfService);
}
}
Subclass in Same Package
// Manager.java (same package)
public class Manager extends BaseEmployee {
public Manager() {
this.department = "Management"; // protected access OK
this.yearsOfService = 5;
}
public void conductMeeting() {
promote(); // protected method OK
System.out.println("Leading team in " + department);
}
}
Subclass in Different Package (if allowed)
// com.otherpackage.RemoteManager.java
// public class RemoteManager extends BaseEmployee {
// public void test() {
// department = "Remote"; // OK - subclass
// }
// }
Best used when you want controlled access in child classes.
4. default Access Modifier (No Keyword)
Accessible only within the same package.
Purpose:
-
Internal use within module
-
Hide from other packages
Example:
class Car { // default class
String model = "Honda"; // default variable
void showModel() { // default method
System.out.println(model);
}
}
// ❌ Not accessible, because default members are package-private.
Example 2: Internal Helper Class
// EmployeeValidator.java (same package, no modifier)
class EmployeeValidator {
static boolean isValidId(String id) {
return id != null && id.startsWith("EMP");
}
static boolean isEligibleForBonus(int years) {
return years >= 3;
}
}
Using in Same Package
// HRDepartment.java (same package)
public class HRDepartment {
public void validateNewHire(String id, int years) {
if (EmployeeValidator.isValidId(id)) {
System.out.println("ID valid");
}
if (EmployeeValidator.isEligibleForBonus(years)) {
System.out.println("Bonus eligible");
}
}
}
Default access is useful for package-level organization.
Access Modifier Comparison Table
| Access Modifier | Same Class | Same Package | Subclass (Other Package) | Other Package |
|---|---|---|---|---|
| public | ✔ | ✔ | ✔ | ✔ |
| protected | ✔ | ✔ | ✔ | ❌ (except through inheritance) |
| default | ✔ | ✔ | ❌ | ❌ |
| private | ✔ | ❌ | ❌ | ❌ |
|
Modifier |
Visibility |
|---|---|
|
public |
Accessible from everywhere |
|
protected |
Accessible within same package + subclasses (even in different packages) |
|
default (no keyword) |
Accessible only within same package |
|
private |
Accessible only within same class |
Real-Life Analogy (Easy Understanding)
| Modifier | Real-Life Example |
|---|---|
| public | Public Park → Anyone can enter |
| private | Your Bedroom → Only you can access |
| protected | Your House → Only family members (children) have access |
| default | Society Compound → Only people living in the same building can access |
Why Access Modifiers Are Important?
-
Improve security of data (Encapsulation)
-
Prevent misuse of variables/methods
-
Control visibility across packages
-
Help write clean & maintainable code
-
Protect sensitive information
Complete Example (All Modifiers Together)
package p1;
public class Person {
public String name = "Rahul"; // public
private int age = 25; // private
protected String city = "Pune"; // protected
String country = "India"; // default
public void show() {
System.out.println(name);
System.out.println(age);
System.out.println(city);
System.out.println(country);
}
}
package p2;
import p1.Person;
public class Test extends Person {
public static void main(String[] args) {
Person p = new Person();
System.out.println(p.name); // ✔ public
// System.out.println(p.age); // ❌ private
// System.out.println(p.country);// ❌ default
// System.out.println(p.city); // ❌ protected (not via object)
Test t = new Test();
System.out.println(t.city); // ✔ protected via inheritance
}
}
Conclusion
Java provides four Access Modifiers — public, private, protected, and default — to control visibility and secure your classes.
They help developers implement encapsulation, protect data, maintain clean structure, and avoid unwanted access.
Use them wisely to make your Java code professional, safe, and maintainable.
You now fully master Access Modifiers with a secure, real-world HR system!
Keep building — happy coding! ![]()
.png)