11
JulAccess Modifiers in Java: Default, Private, Public, Protected
Access modifiers in Java decide who can access classes, methods, and variables in your code. They play a key role in organizing your program, protecting data, and controlling visibility across different parts of your application. By using access modifiers wisely, you embrace the principle of encapsulation—a core concept of object-oriented programming that leads to more secure, maintainable, and scalable code. Whether you're a beginner or aiming to write professional-grade Java programs, understanding access modifiers is a must.
In this Java tutorial, we will learn about Access Specifiers in Java. We will discuss the meaning of an access specifier, give examples from real-world situations, and look at various types of access modifiers, such as default, private, protected, and public.
If you aren't clear with the following concepts, do refer to them to understand Java Access Modifiers completely: |
What is an Access Modifier in Java?
Access Modifier in Java in Java are keywords that define the visibility or accessibility of classes, methods, variables, and constructors within a program. They guide the Java compiler on where a particular element can be accessed from, ensuring better control and encapsulation in your code. Java provides four main access modifiers:
- public: The element is accessible from any class, regardless of the package.
- private:The element is accessible only within the same class.
- protected: The element is accessible within the same package and in subclasses, even in different packages.
- default (no modifier): Accessible only within the same package (also called package-private).
Java Access Modifiers Overview
Modifier | Class | Package | Subclass | Other-Packages | Description |
public | ✔ | ✔ | ✔ | ✔ | Accessible from anywhere. |
protected | ✔ | ✔ | ✔ | ✘ | Accessible within the same package and subclasses, even in other packages. |
default | ✔ | ✔ | ✘ | ✘ | Accessible only within the same package. No keyword is needed; it’s the default accessibility. |
private | ✔ | ✘ | ✘ | ✘ | Accessible only within the same class. |
Key Notes:
- Subclass access for protected: It allows access when subclassing, even if the subclass resides in a different package. However, access is limited to inherited members.
- Default access (no modifier): Often called "package-private." It's the default if no access modifier is specified.
- Private: Strictly confined to the declaring class.
Read More: Top 50 Java Interview Questions |
Real-Life Example of an Access Modifier in Java
As a real-time example, we can choose Facebook, where users can control their posts.
There are three types of Access Modifiers: "Public Access Specifier," "Protected Access Specifier," and "Private Access Specifier."
- If anyone wants to make the status visible to the public, they can choose "Public Access Specifiers."
- If anyone wants to make their status visible to only their friends, it is called a "Protected Access Specifier."
- Lastly, if someone wants to make the status visible only to themselves, they can use the "Private Access Specifier."
Types of Access Modifiers in Java
There are four types of Access Modifier in Java:
- Default Access Modifier
- Private Access Modifier
- Protected Access Modifier
- Public Access Modifier
1. Default Access Modifier in Java
In Java, the default access modifier is automatically applied when no other access modifier (public, private, or protected) is specified. Members with default access are accessible only within the same package, meaning they cannot be accessed from classes in other packages. This helps maintain a level of encapsulation within a logical grouping of related classes.
Read More: What is a Package in Java? |
Example
class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.balance = 1000.0;
account.deposit(500.0);
System.out.println("Balance: " + account.balance); // Accessible because Main is in the same package
}
}
// File: BankAccount.java
class BankAccount {
double balance; // Default access modifier (package-private)
void deposit(double amount) { // Default access modifier (package-private)
balance += amount;
}
}
Explanation
The balance variable and deposit method of BankAccount in this example have default (package-private) access, meaning that Main, which is in the same package, can access them. The default access level is illustrated by the Main class, which initializes the balance, deposits money, and prints the updated balance.
Output
Balance: 1500.0
2. Private Access Modifier in Java
The private access modifier restricts access to class members within the same class only. When a variable or method is declared private, it cannot be accessed from outside its own class. This modifier is essential for data hiding and encapsulation, helping to protect internal implementation details and maintain control over how data is accessed or modified.
Example
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
balance = initialBalance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println(amount + " deposited successfully.");
} else {
System.out.println("Invalid amount for deposit.");
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println(amount + " withdrawn successfully.");
} else {
System.out.println("Invalid amount or insufficient balance.");
}
}
public void displayBalance() {
System.out.println("Current balance: " + balance);
}
public static void main(String[] args) {
// Example usage
BankAccount account = new BankAccount(1000);
account.displayBalance();
account.deposit(500);
account.displayBalance();
account.withdraw(200);
account.displayBalance();
account.withdraw(1500);
}
}
Explanation
The BankAccount class employs private access for balance to enable secure data management. Deposit and withdraw methods validate the balance, while displayBalance displays the current amount. The main method demonstrates these actions by showing how encapsulation controls and protects data within the class.
Output
Current balance: 1000.0
500.0 deposited successfully.
Current balance: 1500.0
200.0 withdrawn successfully.
Current balance: 1300.0
Invalid amount or insufficient balance.
3. Protected Access Modifiers in Java
The protected access modifier allows access to class members within the same package and also to subclasses in other packages. It offers a level of access broader than private but more restricted than public. This modifier is commonly used when you want to allow inheritance-based access to certain members while still preventing access from unrelated external classes.
Read More: Hierarchical Inheritance in Java |
Example
// Base class
class Vehicle {
protected String brand; // protected member variable
protected void displayDetails() {
System.out.println("Brand: " + brand);
}
}
// Derived class
class Car extends Vehicle {
private int mileage; // private member variable specific to Car
public Car(String brand, int mileage) {
this.brand = brand; // accessing protected member from superclass
this.mileage = mileage;
}
public void displayCarDetails() {
displayDetails(); // accessing protected method from superclass
System.out.println("Mileage: " + mileage);
}
}
// Main class to test inheritance and protected access
class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota", 30);
myCar.displayCarDetails();
}
}
Explanation
There are two classes in this Java example: Parent and Child. The notion of inheritance and protected access is shown by the reality that the Child class derives from the Parent class and can access the protected method "display()" of the Parent class thanks to the protected access modifier.
Output
Brand: Toyota
Mileage: 30
4. Public Access Modifier in Java
The public access modifier allows classes, methods, and variables to be accessed from anywhere in the program, regardless of the package they belong to. When a member is declared public, it becomes universally accessible across all classes and packages. This modifier is typically used when you want to expose functionality or data for widespread use throughout the application.
Example
// File: Main.java
class Main {
public static void main(String[] args) {
Book book = new Book();
book.title = "The Great Gatsby";
book.setAuthor("F. Scott Fitzgerald");
System.out.println("Title: " + book.title);
System.out.println("Author: " + book.getAuthor());
}
}
// File: Book.java
class Book {
public String title; // Public access modifier
private String author; // Private access modifier
public void setAuthor(String author) { // Public access modifier
this.author = author;
}
public String getAuthor() { // Public access modifier
return this.author;
}
}
Explanation
This code defines the Main and Book classes. Main creates a new instance of Book, using public methods (setAuthor) to set its title and author and public access (title and getAuthor) to obtain it. A book that allows for private access to control direct modification encapsulates the author field.
Output
Title: The Great Gatsby
Author: F. Scott Fitzgerald
Go through the following Interview articles: |
Advantages of Access Modifiers in Java
- Encapsulation & Security – Protect sensitive data by hiding it from outside access.
- Better Code Structure – Helps organize code into well-defined modules.
- Improved Maintainability – Limits what can be accessed or modified, reducing bugs.
- Controlled Inheritance – Allows selective visibility across packages and subclasses.
- API Safety – Exposes only necessary methods, keeping internal logic hidden.
- Avoids Accidental Changes – Prevents misuse of internal class members.
Disadvantages of Access Modifiers in Java
- Overuse Can Limit Flexibility – Making too many members private or protected can restrict reuse or extension.
- Can Cause Tight Coupling – Improper use may force developers to write tightly dependent code or use workarounds (like getters/setters).
- Increased Complexity – Beginners may find it confusing to decide the right modifier, especially in large projects.
- Harder Debugging Across Packages – Restricted access may make it difficult to trace or debug behavior between classes in different packages.
- Slows Down Development (Initially) – Overthinking access levels can delay coding in the early stages of a project.
Java Access Modifiers with Method Overriding
1. Access Modifier Rules in Overriding
- Cannot reduce visibility: When overriding a method, the subclass cannot use a more restrictive access modifier than the one used in the superclass. Example: A public method in the superclass cannot be overridden as protected or private.
- Can increase visibility: The subclass can use a less restrictive (more visible) access modifier when overriding.Example: A protected method in the superclass can be overridden as public in the subclass.
2. Modifier Behavior with Overriding
Access Modifier in Superclass | Allowed in Subclass | Notes |
public | public | Visibility must stay the same (public). |
protected | protected, public | Visibility can increase but cannot decrease. |
default (package-private) | default, protected, public | Overriding is allowed within the same package; visibility can increase. |
private | It cannot be overridden | A private method is not inherited; it is treated as a new method in the subclass. |
3. Key Example
class SuperClass {
protected void display() {
System.out.println("Superclass display method");
}
}
class SubClass extends SuperClass {
@Override
public void display() { // Increasing visibility from protected to public
System.out.println("Subclass display method");
}
}
public class Test {
public static void main(String[] args) {
SuperClass obj = new SubClass(); // Polymorphism in action
obj.display(); // Outputs: Subclass display method
}
}
Output
Subclass display method
Note: In the above code, you have to write the file name as the class name (Test.java) |
Guide on when to use each access modifier in Java
- default (no modifier) – "Keep it in the family (package)"
If you don’t write any access modifier at all, Java applies default access. This means the code is accessible only within the same package. It's a good choice when you're working with several classes that are closely related but shouldn't be exposed outside that group.
Common use: Utility classes or methods meant for use inside a module or package.
- private – "For your class's eyes only"
Use private when something inside a class is meant to stay hidden—like a class's personal data or internal helper methods. If no other class should touch or change it directly, private is the safest choice.
Common use: Class variables like balance, password, or internal calculations.
- protected – "Family and future generations"
Protected access sits between private and public. It allows access within the same package and also by subclasses, even if they're in different packages. It’s mostly useful when you expect other classes to extend yours and override some behavior.
Common use: Methods that child classes should modify or reuse, like calculateBonus() in a base Employee class.
- public – "Open to everyone"
Use public when you want your class, method, or variable to be accessible from anywhere in your project or even by external code (like in a library). Choose this only when you’re confident that the functionality needs to be universally available.
Common use: Entry-point methods like main(), or APIs used across different modules.
Common Mistakes and Compiler Errors with Access Modifiers in Java:
- Trying to override a method with reduced visibility.
- Declaring a top-level class as private or protected.
- Accessing private members from another class.
- Assuming protected means only subclass access.
- Using private or protected modifiers in interfaces incorrectly.
- Using private or protected constructors without understanding their effect.
Conclusion
In conclusion, access modifiers in Java are essential for controlling visibility and protecting data. They help in building secure, organized, and well-structured programs by limiting how different parts of the code interact. Choosing the right access modifier (private, protected, public, or default) is key to writing clean and maintainable Java code.
To deepen your understanding and enhance your skills, consider enrolling in our Free Java Certification Course, which offers comprehensive learning and certification to support your Java journey. And enhance your knowledge with our Free Technology Courses.
💡 Test your Python slicing skills with this quiz!
Q 1: What does the slice operation a[2:5] do on a list a?
FAQs
Take our Java skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.