Access modifiers in Java

In Java, access specifiers (also called access modifiers) define the visibility and accessibility of classes, methods, variables, and constructors. They control which parts of a program can access certain members of a class. Java has four main access specifiers:


1. public

  • Visibility: Everywhere, i.e., from any other class or package.
  • Usage: When you want a class, method, or variable to be accessible universally.
  • Example:
public class MyClass {
    public int number;
    
    public void display() {
        System.out.println("Hello");
    }
}

2. private

  • Visibility: Only within the same class.
  • Usage: When you want to encapsulate data, restricting direct access from outside the class.
  • Example:
class MyClass {
    private int number;
    
    private void display() {
        System.out.println("Hello");
    }
    
    // Public method to access private members
    public int getNumber() {
        return number;
    }
}

3. protected

  • Visibility: Same package + subclasses (even if they are in a different package).
  • Usage: For inheritance, when you want derived classes to access members, but not everyone.
  • Example:
class Parent {
    protected int number;
}

class Child extends Parent {
    void show() {
        System.out.println(number); // Accessible because it's protected
    }
}

4. Default (no modifier)

  • Visibility: Only within the same package.
  • Usage: When you omit any access specifier, it’s called package-private or default access.
  • Example:
class MyClass {
    int number; // default access
}

Summary Table:

ModifierSame ClassSame PackageSubclassAnywhere
private
default
protected
public

Leave a Reply