Access Modifiers in Java: Default, Private, Public, Protected

Access Modifiers in Java: Default, Private, Public, Protected

07 Jun 2025
Intermediate
28.8K Views
23 min read
Learn with an interactive course and practical hands-on labs

Free Java Course With Certificate

Access specifiers in Java define the visibility and accessibility of class members, allowing developers to control access to variables, methods, and constructors. Understanding access specifiers in Java is essential for implementing proper encapsulation and ensuring security in object-oriented programming. Java loops can use these access specifiers in Javato give the program security and authorization.

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 is a keyword that defines the visibility level of classes, methods, variables, and constructors. It tells the Java compiler where a particular element can be accessed from in the program. Java has four access modifiers: public, private, protected, and default (no keyword).

  • public: The element is accessible from any class in any 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

ModifierClassPackageSubclassOther-PackagesDescription
publicAccessible from anywhere.
protectedAccessible within the same package and subclasses, even in other packages.
defaultAccessible only within the same package. No keyword is needed; it’s the default accessibility.
privateAccessible 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."

Real Life example of an Access Modifier in Java?

Types of Access Modifiers in Java

There are four types of Access Modifier in Java:

  1. Default Access Modifier
  2. Private Access Modifier
  3. Protected Access Modifier
  4. Public Access Modifier

1. Default Access Modifier in Java

In Java, the default access modifier is applied automatically to classes, methods, and data members when no access modifier is specified. This indicates that specific parts are only accessible from within the package in which they are defined.

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 in Java is used to restrict access to class members. When a variable or method is marked as private, it can be accessed only within the same class. This helps in data hiding and encapsulation, keeping internal details secure.

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 in Java allows access to class members within the same package and also to subclasses in other packages. It provides more access than private but less than public. This is commonly used when you want to share data with subclasses while still limiting access to unrelated 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 in Java allows class members to be accessed from anywhere in the program. When a method, class, or variable is declared as public, it is visible to all other classes, even in different packages. This modifier is used when you want to make something universally accessible 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:

Java Access Modifiers with Method Overriding

1. Access Modifier Rules in Overriding

  • Cannot reduce visibility: The overridden method in the subclass must have the same or higher visibility compared to the method in the superclass.
  • Can increase visibility: For example, a protected method in the superclass can be overridden as public in the subclass.

2. Modifier Behavior with Overriding

Access Modifier in SuperclassAllowed in SubclassNotes
publicpublicVisibility must stay the same (public).
protectedprotected, publicVisibility can increase but cannot decrease.
default (package-private)default, protected, publicOverriding is allowed within the same package; visibility can increase.
privateIt cannot be overriddenA 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)
    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?

    • Extracts all elements
    • Extracts elements from index 2 to 5
    • Extracts first 5 elements
    • Extracts elements from index 2 to 4

    FAQs

     The public access modifier is most frequently used in Java to define methods and classes that must be accessible from any other class. 

    Both terms are used interchangeably; there are no distinctions. The official name is "access modifier," although the more recent term is "specifier."

     Use protected when you want to allow access to the member variables and methods within the same package and by subclasses. Use private when you want to restrict access to the member variables and methods to the defining class only.

    They provide limitations and assign accessibility to class members, preventing direct access from outside functions.

     Yes, access modifiers are compatible with Java classes. Classes can be declared with public or default (package-private) access modifiers, which control their visibility within the application. 
    Share Article
    About Author
    Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

    Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

    Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
    Live Training - Book Free Demo
    Advanced Full-Stack .NET Developer with Gen AI Certification Training
    15 Jun
    08:30PM - 10:30PM IST
    Checkmark Icon
    Get Job-Ready
    Certification
    ASP.NET Core Certification Training
    15 Jun
    08:30PM - 10:30PM IST
    Checkmark Icon
    Get Job-Ready
    Certification
    Azure Developer Certification Training
    16 Jun
    07:00AM - 09:00AM IST
    Checkmark Icon
    Get Job-Ready
    Certification
    .NET Solution Architect Certification Training
    21 Jun
    10:00AM - 12:00PM IST
    Checkmark Icon
    Get Job-Ready
    Certification
    Full-Stack Azure AI Engineer Certification Training Program
    21 Jun
    05:30PM - 07:30PM IST
    Checkmark Icon
    Get Job-Ready
    Certification
    Accept cookies & close this