Access Modifier in Java

There are four access modifiers in Java:

  1. public - A class, method, or field that is declared public can be accessed from any other class, regardless of the package in which it is defined.
  2. protected - A class, method, or field that is declared protected can be accessed within the package in which it is defined and by subclasses of the class in which it is defined.
  3. default (package-private) - A class, method, or field that has no access modifier is said to have default (or package-private) access. It can be accessed only within the package in which it is defined.
  4. private - A class, method, or field that is declared private can be accessed only within the class in which it is defined.

Here is an example that demonstrates the use of these access modifiers:

package com.example;

public class MyClass {
  public int x;  // visible to any class
  protected int y;  // visible to MyClass and its subclasses
  int z;  // visible to classes in the same package as MyClass
  private int w;  // only visible to MyClass
}

In this example, the field x is visible to any class because it is declared as public. The field y is visible to MyClass and its subclasses because it is declared as protected. The field z is visible to classes in the same package as MyClass because it has default (or package-private) access. Finally, the field w is only visible to MyClass because it is declared as private.