DEV Community

MOHAMED ABDULLAH
MOHAMED ABDULLAH

Posted on

Access Modifiers in Java

n Java, access modifiers are keywords used to define the visibility or scope of classes, methods, constructors, and variables. They play a crucial role in encapsulation, one of the core principles of object-oriented programming (OOP).

Modifier Class Package Subclass World
public
protected
(default)
private

1, public
The member is accessible from anywhere.

No restriction on access.

Example:

public class Car {
public String brand = "Tesla";

public void display() {
    System.out.println("Brand: " + brand);
}

public static void main(String[] args) {
    Car car = new Car();
    car.display();
}
Enter fullscreen mode Exit fullscreen mode

}
output;
Brand: Tesla

  1. private The member is accessible only within the class it is declared in.

Most restrictive access level.

✅ Example:

public class BankAccount {
private double balance = 1000;

private void showBalance() {
    System.out.println("Balance: " + balance);
}

public static void main(String[] args) {
    BankAccount account = new BankAccount();
    // account.showBalance(); // ❌ Compilation Error
}
Enter fullscreen mode Exit fullscreen mode

}
output:
Compilation Error:
showBalance() has private access in BankAccount

Use private for variables/methods that shouldn't be accessed directly from outside the class.

  1. protected The member is accessible:

Within the same package

In subclasses, even if they're in different packages

Example:
class Animal {
protected void sound() {
System.out.println("Animal makes a sound");
}
}

public class Dog extends Animal {
public void bark() {
sound(); // Accessible because it's protected
}

public static void main(String[] args) {
    Dog dog = new Dog();
    dog.bark();
}
Enter fullscreen mode Exit fullscreen mode

}
output:
Animal makes a sound

4.Default (No Modifier)
When no modifier is specified, it's called default or package-private.

Accessible only within the same package.

Example:
class MyClass {
void show() {
System.out.println("Default access");
}

public static void main(String[] args) {
    MyClass obj = new MyClass();
    obj.show();
}
Enter fullscreen mode Exit fullscreen mode

}
output:
Default access

Members with default access are not accessible outside their package, even by subclasses.

Use Case Modifier
Public API or Utility Methods public
Sensitive Data Fields private
Overridable Behavior for Subclass protected
Internal Package Logic (default)

reference link :
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

Top comments (1)

Collapse
 
khmarbaise profile image
Karl Heinz Marbaise

There does not exist a access modifier default ...