10-πŸ” Access Modifiers in Java β€” Complete Guide (private, default, protected, public)

Introduction

In Java, writing code is not just about making it work β€” it is about making it secure, structured, and maintainable β˜•

Imagine a situation where every variable in your program is accessible from anywhere.
Anyone can modify it. Any part of the code can misuse it.

That would quickly lead to:

  • ❌ Data corruption
  • ❌ Unexpected bugs
  • ❌ Security issues
  • ❌ Difficult debugging

To prevent this, Java provides Access Modifiers πŸ”‘

Access modifiers control where a class, variable, method, or constructor can be accessed from.

This article explains all four access modifiers in detail with clear examples, practical programs, common confusions, and mistakes to avoid.


🧠 What Are Access Modifiers?

Access modifiers define the visibility scope of:

  • Variables
  • Methods
  • Constructors
  • Classes

Java provides four access levels:

1️⃣ private
2️⃣ Default (no keyword)
3️⃣ protected
4️⃣ public


πŸ“Š Access Modifier Comparison Table

ModifierSame ClassSame PackageSubclass (Other Package)Outside Package
privateβœ…βŒβŒβŒ
defaultβœ…βœ…βŒβŒ
protectedβœ…βœ…βœ…βŒ
publicβœ…βœ…βœ…βœ…

This table is extremely important for exams and interviews 🎯


πŸ”’ 1️⃣ Private Access Modifier

πŸ”Ή Definition

private members are accessible only within the same class.

πŸ”Ή Purpose

Used for data hiding and encapsulation.


▢️ Example 1: Private Variable

class Student {

    private int rollNo;

    public void setRollNo(int r) {
        rollNo = r;
    }

    public void display() {
        System.out.println("Roll No: " + rollNo);
    }
}

public class PrivateDemo {
    public static void main(String[] args) {

        Student s = new Student();
        s.setRollNo(101);
        s.display();
    }
}

🧠 Step-by-Step Explanation

  • rollNo is private β†’ cannot be accessed outside class
  • setRollNo() allows controlled modification
  • display() prints value
  • Object interacts through public methods

❌ Common Mistake

s.rollNo = 101; // ❌ Compilation Error

Why?
Because rollNo is private and cannot be accessed outside the class.


🎯 When to Use Private?

  • Always for instance variables
  • When you want controlled access
  • To protect sensitive data

πŸ“¦ 2️⃣ Default Access Modifier (Package-Private)

If no modifier is specified β†’ it becomes default access.

Accessible only within the same package.


▢️ Example 2: Default Access

class Test {

    int value = 50; // default access

    void show() {
        System.out.println("Value: " + value);
    }
}

public class DefaultDemo {
    public static void main(String[] args) {

        Test t = new Test();
        t.show();
    }
}

🧠 Explanation

  • value has default access
  • Accessible within same package
  • Not accessible outside package

❓ Common Confusion

Is default same as private?

❌ No
Default β†’ package-level access
Private β†’ class-level access


🌿 3️⃣ Protected Access Modifier

protected members are accessible:

  • Within same class
  • Within same package
  • In subclasses (even in different package)

Used mainly when inheritance is involved.


▢️ Example 3: Protected Member

class Person {

    protected String name = "Ajay";

    protected void showName() {
        System.out.println("Name: " + name);
    }
}

public class ProtectedDemo {
    public static void main(String[] args) {

        Person p = new Person();
        p.showName();
    }
}

🧠 Explanation

  • name and showName() are protected
  • Accessible inside same package
  • Also accessible in subclasses

❓ Why Use Protected?

When designing for inheritance:

  • Allow subclass access
  • Restrict public exposure

🌍 4️⃣ Public Access Modifier

public members are accessible from anywhere.

Most open access level.


▢️ Example 4: Public Access

class Demo {

    public int number = 100;

    public void display() {
        System.out.println("Number: " + number);
    }
}

public class PublicDemo {
    public static void main(String[] args) {

        Demo d = new Demo();
        d.display();
    }
}

🧠 Explanation

  • number accessible everywhere
  • display() accessible everywhere
  • No restrictions

⚠️ Warning

Making everything public is bad design ❌
It breaks encapsulation and security.


πŸ” Access Modifiers for Classes

Top-level classes can only be:

  • public
  • default

They cannot be:

  • private
  • protected

▢️ Example

public class MyClass {
}

Valid.

private class MyClass {
}

❌ Invalid.


❗ Common Confusions

❓ Why are variables usually private?

To:

  • Prevent direct modification
  • Force controlled access
  • Maintain object integrity

❓ Can private methods be accessed in another class?

❌ No


❓ Can protected members be accessed without inheritance?

Yes, within same package.


❓ What happens if no modifier is written?

Default access applies.


❌ Common Mistakes

❌ Making all variables public

Bad practice.


❌ Confusing default with private

Default β‰  private.


❌ Forgetting encapsulation

public int balance; // ❌ unsafe

❌ Trying to access private members outside class

Compilation error.


πŸ§ͺ Tricky Scenario

class Test {

    private int x = 10;

    void show() {
        System.out.println(x);
    }
}

public class TrickyDemo {
    public static void main(String[] args) {

        Test t = new Test();
        t.show();
    }
}

🧠 Why does this work?

Because show() is inside the class and can access private member.

Package Example:-

πŸ“¦ SAME PACKAGE EXAMPLES (Very Important Section)

To properly understand access modifiers, let’s simulate a same package scenario.

Assume both classes are in:

package mypackage;

πŸ”’ 1️⃣ Private Access Modifier

Private members are accessible only inside the same class.


▢️ Example: Private (Same Package)

File: Student.java

package mypackage;

class Student {

    private int rollNo = 101;

    void show() {
        System.out.println("Roll No: " + rollNo);
    }
}

File: MainClass.java

package mypackage;

public class MainClass {
    public static void main(String[] args) {

        Student s = new Student();
        s.show();         // βœ… Allowed
        // System.out.println(s.rollNo); ❌ Not Allowed
    }
}

🧠 Explanation

  • rollNo is private
  • It can only be accessed inside Student class
  • Even though MainClass is in same package, it CANNOT access private members

πŸ“Œ Private = Class-level access only


πŸ“¦ 2️⃣ Default Access Modifier (Package-Private)

If no modifier is written β†’ default access.

Accessible inside the same package only.


▢️ Example: Default Access (Same Package)

File: Employee.java

package mypackage;

class Employee {

    int id = 1;   // default access

    void display() {
        System.out.println("Employee ID: " + id);
    }
}

File: MainClass.java

package mypackage;

public class MainClass {
    public static void main(String[] args) {

        Employee e = new Employee();
        System.out.println(e.id);   // βœ… Allowed
        e.display();               // βœ… Allowed
    }
}

🧠 Explanation

  • id has default access
  • Both classes are in same package
  • So access is allowed

πŸ“Œ Default = Package-level access


🌿 3️⃣ Protected Access Modifier

Protected members are accessible:

  • Inside same class
  • Inside same package
  • In subclass (even outside package)

▢️ Example: Protected (Same Package)

File: Person.java

package mypackage;

class Person {

    protected String name = "Ajay";

    protected void showName() {
        System.out.println("Name: " + name);
    }
}

File: MainClass.java

package mypackage;

public class MainClass {
    public static void main(String[] args) {

        Person p = new Person();
        System.out.println(p.name);    // βœ… Allowed
        p.showName();                 // βœ… Allowed
    }
}

🧠 Explanation

  • Protected behaves like default inside same package
  • Accessible normally

πŸ“Œ Inside same package β†’ protected = default behavior


🌍 4️⃣ Public Access Modifier

Public members are accessible everywhere.


▢️ Example: Public (Same Package)

File: Demo.java

package mypackage;

public class Demo {

    public int value = 100;

    public void show() {
        System.out.println("Value: " + value);
    }
}

File: MainClass.java

package mypackage;

public class MainClass {
    public static void main(String[] args) {

        Demo d = new Demo();
        System.out.println(d.value);   // βœ… Allowed
        d.show();                     // βœ… Allowed
    }
}

πŸ” Important Clarification

Inside the same package:

  • default β†’ accessible
  • protected β†’ accessible
  • public β†’ accessible
  • private β†’ NOT accessible

🎯 Best Practice Guidelines

βœ” Always make instance variables private
βœ” Provide public getter/setter when needed
βœ” Use protected carefully
βœ” Avoid unnecessary public exposure
βœ” Use default access for package-internal logic


πŸ“Œ Summary Table

ModifierBest Use Case
privateData hiding
defaultPackage-level grouping
protectedInheritance support
publicOpen API exposure

βœ… Conclusion

Access modifiers are the backbone of secure and maintainable Java programming πŸ”

By properly using:

  • private for data hiding
  • default for package control
  • protected for inheritance design
  • public for controlled exposure

You create Java applications that are:

  • Secure πŸ”’
  • Organized πŸ“¦
  • Maintainable πŸ› οΈ
  • Professionally structured πŸš€

Mastering access modifiers is essential for writing high-quality Java code and for excelling in interviews and real-world development.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *