DEV Community

Rajesh Bhola
Rajesh Bhola

Posted on

Part 1 - Member Access Modifiers: public, private, protected, and Default Access

When we create classes in Java, we don't want every variable and method to be accessible from everywhere.

For example, in a banking application:

  • Account balance should not be directly modified by anyone.
  • Payment methods should be accessible to other modules.
  • Internal validation methods should remain hidden.
  • Some methods should be available only to child classes.

Java provides member access modifiers to control the visibility of class members.

Member access modifiers decide:

  • Who can access a variable?
  • Who can call a method?
  • Can a child class access it?
  • Can another package access it?

The four member access levels in Java are:

  1. private
  2. default (package-private)
  3. protected
  4. public

Understanding these modifiers is extremely important for:

  • Writing secure Java applications
  • Applying encapsulation
  • Designing APIs
  • Preparing for Java interviews

What Are Member Access Modifiers?

A member in Java means:

  • Instance variables
  • Static variables
  • Methods
  • Constructors
  • Inner classes

Member access modifiers define the visibility of these members.

Example:

class BankAccount {

    private double balance;

    public void deposit(double amount) {
        balance += amount;
    }

}
Enter fullscreen mode Exit fullscreen mode

Here:

  • balance is private.
  • deposit() is public.

The outside world cannot directly access balance, but it can call deposit().


Why Do We Need Member Access Modifiers?

Without access control, any code could directly modify internal data.

Example:

class BankAccount {

    double balance;

}
Enter fullscreen mode Exit fullscreen mode

Now anyone can do:

BankAccount account = new BankAccount();

account.balance = -50000;
Enter fullscreen mode Exit fullscreen mode

This creates invalid data.

Using modifiers, we can protect important data.

Example:

class BankAccount {

    private double balance;

    public void deposit(double amount) {

        if(amount > 0) {
            balance += amount;
        }

    }

}
Enter fullscreen mode Exit fullscreen mode

Now the class controls how the data changes.

This concept is called:

Encapsulation


Class Visibility Comes First

Before checking member visibility, we must check whether the class itself is visible.

This is one of the most important Java rules.

Consider:

package pack1;

class Customer {

    public void display() {

        System.out.println("Customer details");

    }

}
Enter fullscreen mode Exit fullscreen mode

The method display() is public.

But the class Customer is not public.

Now another package tries:

package pack2;

import pack1.Customer;

class Main {

    public static void main(String[] args) {

        Customer customer = new Customer();

        customer.display();

    }

}
Enter fullscreen mode Exit fullscreen mode

Compile-Time Error

Customer is not public in pack1;
cannot be accessed from outside package
Enter fullscreen mode Exit fullscreen mode

Why?

Even though the method is public:

Method Visibility
        ↓
       public

Class Visibility
        ↓
       default

Result
        ↓
       Not Accessible
Enter fullscreen mode Exit fullscreen mode

The class must be visible first.


Access Checking Order

Java follows this order:

Step 1
Check class visibility

        ↓

Step 2
Check member visibility

        ↓

Step 3
Allow or reject access
Enter fullscreen mode Exit fullscreen mode

Example:

public method
      +
private class

= Cannot access
Enter fullscreen mode Exit fullscreen mode

Both class and member visibility must allow access.


1. Public Members

A member declared with public can be accessed from anywhere.

Conditions:

  • The class must also be accessible.
  • The member must be public.

Example: Public Method

Program 1

package pack1;

public class Customer {

    public void display() {

        System.out.println("Customer details");

    }

}
Enter fullscreen mode Exit fullscreen mode

Program 2

package pack2;

import pack1.Customer;

public class Main {

    public static void main(String[] args) {

        Customer customer = new Customer();

        customer.display();

    }

}
Enter fullscreen mode Exit fullscreen mode

Output

Customer details
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Explanation

Step 1

Customer class is declared public.

Therefore, other packages can access it.

Step 2

display() method is also public.

Therefore, it can be called externally.

Step 3

Main imports the class.

Step 4

The method executes successfully.


Important Rule About Public Members

A public member does not make a non-public class accessible.

Example:

package pack1;

class Customer {

    public void display(){

        System.out.println("Customer");

    }

}
Enter fullscreen mode Exit fullscreen mode

The method is public.

But the class is package-private.

Therefore:

Outside package access

Class ❌
Method ✅

Final Result ❌
Enter fullscreen mode Exit fullscreen mode

2. Default Members (Package-Private)

If no modifier is specified, Java uses default access.

Default members are accessible only within the same package.

Example:

package pack1;

class Customer {

    void display(){

        System.out.println("Customer details");

    }

}
Enter fullscreen mode Exit fullscreen mode

Here:

  • Class → default
  • Method → default

Access Within Same Package

package pack1;

public class Main {

    public static void main(String[] args) {

        Customer customer = new Customer();

        customer.display();

    }

}
Enter fullscreen mode Exit fullscreen mode

Output

Customer details
Enter fullscreen mode Exit fullscreen mode

Access From Different Package

package pack2;

import pack1.Customer;

public class Main {

    public static void main(String[] args) {

        Customer customer = new Customer();

        customer.display();

    }

}
Enter fullscreen mode Exit fullscreen mode

Compile-Time Error

Customer is not public in pack1;
cannot be accessed from outside package
Enter fullscreen mode Exit fullscreen mode

Default Access Memory Trick 🧠

Remember:

Default = Package Friends Only
Enter fullscreen mode Exit fullscreen mode

A default member is visible only to classes living in the same package.


3. Private Members

A private member can be accessed only inside the same class.

Example:

class Customer {

    private double balance = 5000;

    private void validateAccount(){

        System.out.println("Validation completed");

    }

}
Enter fullscreen mode Exit fullscreen mode

Outside code cannot access these members.


Example

class Customer {

    private String name = "Rajesh";

}

public class Main {

    public static void main(String[] args) {

        Customer customer = new Customer();

        System.out.println(customer.name);

    }

}
Enter fullscreen mode Exit fullscreen mode

Compile-Time Error

name has private access in Customer
Enter fullscreen mode Exit fullscreen mode

Why Use Private Members?

Private members support:

  • Data hiding
  • Encapsulation
  • Security
  • Controlled access

Example:

class BankAccount {

    private double balance;


    public void deposit(double amount){

        if(amount > 0){

            balance += amount;

        }

    }

}
Enter fullscreen mode Exit fullscreen mode

The object controls its own state.


Private Methods and Inheritance

Private methods are not visible in child classes.

Example:

class Parent {

    private void display(){

        System.out.println("Parent method");

    }

}


class Child extends Parent {

}
Enter fullscreen mode Exit fullscreen mode

The child class cannot access display().


Why is private abstract Illegal?

Abstract methods must be implemented by child classes.

Example:

abstract class Parent {

    private abstract void display();

}
Enter fullscreen mode Exit fullscreen mode

Compile-Time Error

illegal combination of modifiers:
abstract and private
Enter fullscreen mode Exit fullscreen mode

Reason:

abstract
   ↓
Needs inheritance

private
   ↓
No inheritance visibility
Enter fullscreen mode Exit fullscreen mode

They contradict each other.


4. Protected Members

protected is the most misunderstood access modifier.

Rule:

protected = default + child access
Enter fullscreen mode Exit fullscreen mode

A protected member can be accessed:

Same Package

✅ Any class

Different Package

✅ Only child classes


Protected Within Same Package

Example:

package pack1;

public class Employee {


    protected void display(){

        System.out.println("Employee details");

    }

}
Enter fullscreen mode Exit fullscreen mode

Another class:

package pack1;

class Manager extends Employee {


    public static void main(String[] args){

        Employee employee = new Employee();

        employee.display();


        Manager manager = new Manager();

        manager.display();

    }

}
Enter fullscreen mode Exit fullscreen mode

Output

Employee details
Employee details
Enter fullscreen mode Exit fullscreen mode

Protected From Different Package

Outside package:

package pack2;

import pack1.Employee;


class Manager extends Employee {


    public static void main(String[] args){

        Manager manager = new Manager();

        manager.display();

    }

}
Enter fullscreen mode Exit fullscreen mode

This works.


Protected Access Rule Outside Package

From another package:

Allowed:

Manager manager = new Manager();

manager.display();
Enter fullscreen mode Exit fullscreen mode

Not allowed:

Employee employee = new Employee();

employee.display();
Enter fullscreen mode Exit fullscreen mode

Why?

Because protected access outside the package works only through the child reference.


Access Modifier Comparison Table

Visibility Same Class Same Package Child Same Package Non-Child Different Package Child Different Package Non-Child
private
default
protected
public

Accessibility Order

From least accessible to most accessible:

private
   ↓
default
   ↓
protected
   ↓
public
Enter fullscreen mode Exit fullscreen mode

Remember:

private < default < protected < public
Enter fullscreen mode Exit fullscreen mode

Recommended Access Modifiers

For Variables

Recommended:

private
Enter fullscreen mode Exit fullscreen mode

Why?

Because variables should usually be protected through encapsulation.

Example:

private double salary;
Enter fullscreen mode Exit fullscreen mode

For Methods

Recommended:

public
Enter fullscreen mode Exit fullscreen mode

when the method represents the class's external behavior.

Example:

public void processPayment()
Enter fullscreen mode Exit fullscreen mode

Common Beginner Mistakes

Mistake 1: Thinking Public Method Means Public Access

Incorrect assumption:

"The method is public, so everyone can access it."

Not always.

The class must also be accessible.


Mistake 2: Confusing Default With Public

Incorrect:

class Customer {

}
Enter fullscreen mode Exit fullscreen mode

This is not public.

It is package-private.


Mistake 3: Accessing Protected Members Using Parent Reference Outside Package

Incorrect:

Employee employee = new Manager();

employee.display();
Enter fullscreen mode Exit fullscreen mode

Correct:

Manager manager = new Manager();

manager.display();
Enter fullscreen mode Exit fullscreen mode

Interview Questions

1. What are the four access modifiers in Java?

Answer:

  • private
  • default
  • protected
  • public

2. Which is the most restrictive access modifier?

Answer:

private


3. Which is the least restrictive access modifier?

Answer:

public


4. Can private methods be overridden?

Answer:

No.

Private methods are not visible to child classes.


5. Why is protected called default + kids?

Answer:

Because:

  • Same package → everyone can access
  • Different package → only child classes can access

6. Can a public method exist inside a private class?

Yes.

But the method cannot be accessed outside because the class itself is hidden.


Quick Memory Trick 🧠

Remember:

PPPP Rule

Private
 ↓
Package
 ↓
Protected
 ↓
Public
Enter fullscreen mode Exit fullscreen mode

Visibility increases as we move downward.


Key Takeaways

  • Member modifiers control access to variables, methods, constructors, and inner classes.
  • Always check class visibility before member visibility.
  • public members are accessible everywhere if the class is visible.
  • Default members are accessible only within the same package.
  • Private members are accessible only inside the same class.
  • Protected members work as default + child access.
  • Recommended variable modifier: private.
  • Recommended public API methods: public.
  • Access order:
private < default < protected < public
Enter fullscreen mode Exit fullscreen mode

If you found this guide helpful, leave a ❤️ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.

Happy Coding!

Top comments (0)