Junior — Middle
What are the access levels in Java and how are they used?
sobes.tech AI
Answer from AI
In Java, there are four main access levels (access modifiers) that determine the visibility of classes, methods, and fields:
-
public — accessible from anywhere. An element with this modifier is available from any other class.
-
protected — accessible within the same package and in subclasses (even if they are in different packages).
-
default (package-private) — if no modifier is specified, access is only within the current package.
-
private — accessible only within the class itself.
Example of usage:
public class Example {
public int publicField; // accessible everywhere
protected int protectedField; // accessible within package and subclasses
int defaultField; // accessible only within the package
private int privateField; // accessible only within the class
}
These levels help encapsulate data and control access to it, which improves security and code structure.