Sobes.tech
Junior — Middle

What are the levels of access to class members in Java?

sobes.tech AI

Answer from AI

In Java, there are four main access levels for class members (fields and methods):

  1. public — accessible from anywhere, any class.
  2. protected — accessible within the same package and in subclasses (even if in different packages).
  3. default (package-private) — if no access modifier is specified, accessible only within the same package.
  4. private — accessible only within the class itself, not outside.

Example:

public class Example {
    public int publicField;
    protected int protectedField;
    int defaultField; // package-private
    private int privateField;
}

Choosing the access level helps encapsulate data and control the visibility of class members.