Java, access modifiers are keywords used to define the visibility (or accessibility) of classes, methods, and variables parts of the program.
Access control
When writing code in Java, one of the key concepts you'll often hear about is access control. This is where access modifiers come into play. They help you control who can see and use the various parts of your code—such as variables, methods, and classes.

🚪 What Are Access Modifiers?

Access modifiers are keywords in Java that define the visibility or scope of classes, methods, constructors, and variables.

Image description

🔍 1. public – Open to All

If public, it's accessible from anywhere in your program.
Eg:

public class Car {
    public String brand;

    public void drive() {
        System.out.println("Driving...");
    }
}

brand and drive() can be accessed from any class.

🔐 2. private – Just for Me

If you want something to be strictly hidden from other classes, you use private.

public class BankAccount {
    private double balance;

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

    public double getBalance() {
        return balance;
    }
}

The balance variable can't be directly accessed from outside the class. You can only read or modify it through the public methods.

🛡️ 3. protected – Family Access (TBD)

When a member is protected, it's visible within the same package or by subclasses, even if they're in different packages.
Eg:

class Animal {
    protected void makeSound() {
        System.out.println("Animal sound");
    }
}

class Dog extends Animal {
    public void bark() {
        makeSound(); // This is allowed
        System.out.println("Bark!");
    }
}

📦 4. Default (No Modifier)

If you don’t use any modifier, it defaults to package-private. This means it can only be accessed by classes in the same package. Can we also access in same package.

class Book {
    String title; // default access

    void read() {
        System.out.println("Reading...");
    }
}

💡 Why Are Access Modifiers Important?

  • Encapsulation – Hides internal implementation details.
  • Security – Keeps sensitive data safe from unintended changes.
  • Maintainability – Makes code easier to update and debug.
  • Cleaner Code – Helps you design better APIs and reusable components.

🧵 In Conclusion

Access modifiers might seem like a small part of Java, but they play a huge role in keeping your code organized, secure, and efficient.