Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Access Modifiers in Java: Default, Private, Public, Protected

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

15 Dec 2024
Intermediate
22.9K Views
20 min read
Learn with an interactive course and practical hands-on labs

Free Java Course With Certificate

Access Modifiers in Java

Access modifiers in Java commonly manage a code block's permissions. Describing which portions of the program will be accessible to users and other participants helps make the program more visible and accessible. Java loops can use these access modifiers to give the program security and authorization.

In this Java tutorial, we will learn about Java Access Specifiers. 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?

  • Java access modifiers control which classes, methods, interfaces, constructors, and variables are visible, which is essential for security and encapsulation.
  • They consist of default (package-private), protected, private, and public.
  • Proficiency with these modifiers guarantees secure data protection and effective communication between Java components.
  • The Java developer may need to make some unwanted adjustments to the code before releasing it for public use.
  • To avoid situations like this one, developers use access modifiers to manage program access.
  • Depending on their needs, they divide the code into protected, private, and public parts.

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

  • Private means that only the class has direct access to the method or variable.
  • It's like having a room where only class members (methods and variables) can enter.
  • It protects sensitive information by keeping it hidden from other classes.
  • Imagine having a lock on a drawer that only the class knows how to open.
  • Use private for things that should be kept within the class and not accessed from outside.
  • It is about maintaining privacy and security within the class boundaries.
Read More: Java Programmer Salary In India

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 modifier allows subclass members to access their superclass's protected fields and functions, promoting code reuse and extension.
  • It makes members accessible to subclasses and other classes in the same package, preserving encapsulation while providing restricted visibility.
  • It also enables hierarchical relationships by allowing subclasses to inherit and override superclass methods, encouraging flexibility and modular design.
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 specifier uses the "public" keyword to make data public in Java. It creates a method or data member that is accessible to everyone and every platform.

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
Also Read:
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 Superclass                        Allowed in Subclass                                       Notes
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.
privateCannot 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)
    Summary

    Understanding Java access modifiers is essential for developing safe and efficient software. Proper encapsulation and regulated interaction between various program components are ensured by understanding and using default, protected, private, and public access levels. These moderators prevent unwanted access and alteration, preserving data security and integrity. Enjoy our free Java Course with Certification for your better Java development future.

    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.
    Accept cookies & close this