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

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

16 Jul 2024
Intermediate
17.5K Views
15 min read
Learn via Video Course & by Doing Hands-on Labs

Java Online Course Free with Certificate (2024)

Access Specifiers 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 what they need, they divide the code into parts that are protected, private, and public.

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

Diagram of Types of Access Modifiers in Java

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 Illustrating Default Access Modifier in Java


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 Illustrating Private Access Modifier in Java


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

protected modifier allows subclass members to access their superclass's protected fields and functions, which promotes 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 Illustrating Protected Access Modifier in Java


// 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 accessible to everyone and every platform.

Example Illustrating Public Access Modifier


// 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

Access Modifiers in Java in a Nutshell

Diagram for Access Modifiers in Java in a Nutshell
Also Read:
Go through the following Interview articles:
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.

Get yourselves enrolled in our expert-designed Java Programming Course and get a chance to learn and implement the concepts in Java to become a successful programmer.

FAQs

Q1. What access modifier is most frequently used?

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

Q2. What distinguishes a access specifier from an access modifier?

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

Q3. When should I use protected vs. private?

 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.

Q4. What benefit do access modifiers offer?

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

Q5. Are access modifiers compatible with classes?

 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

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Generative AI For Software Developers Jul 20 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Angular Certification Course Jul 20 SAT, SUN
Filling Fast
06:00PM to 08:00PM (IST)
Get Details
Azure Master Class Jul 20 SAT, SUN
Filling Fast
03:00PM to 05:00PM (IST)
Get Details
ASP.NET Core Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Software Architecture and Design Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Solution Architect Certification Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Azure Developer Certification Training Jul 28 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Data Structures and Algorithms Training with C# Jul 28 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Angular Certification Course Aug 11 SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
ASP.NET Core Project Aug 24 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this