Sobes.tech
Junior

Tell about access modifiers in Java.

sobes.tech AI

Answer from AI

In Java, there are four main access modifiers that determine the visibility of classes, methods, and fields:

  • public — accessible from anywhere, from any class.
  • protected — accessible within its package and in subclasses even if they are in different packages.
  • default (package-private) — if no modifier is specified, accessible only within the current package.
  • private — accessible only within the class itself.

Example:

public class Example {
    public int a;       // accessible to everyone
    protected int b;    // accessible within the package and in subclasses
    int c;              // default, accessible within the package
    private int d;      // accessible only within the class
}

Access modifiers help implement encapsulation by restricting visibility and protecting the internal state of objects.