Sobes.tech
Junior — Middle

Explain the differences between private, default (package-private), protected, and public access levels in programming languages like Java.

sobes.tech AI

Answer from AI

In Java, access levels determine where class members (fields, methods) can be used:

  • private: accessible only within the class itself. No other classes, even in the same package, can see these members.

  • default (package-private): if no modifier is specified, access is allowed to all classes in the same package, but not from other packages.

  • protected: access is allowed to classes in the same package and subclasses (even if they are in different packages).

  • public: access is allowed from anywhere, without restrictions.

Example:

package example;

public class MyClass {
    private int privateVar; // accessible only within MyClass
    int defaultVar;         // accessible within the package example
    protected int protectedVar; // accessible within the package and subclasses
    public int publicVar;    // accessible from everywhere
}

Thus, access levels help control encapsulation and data security.