☕ Java Beginner

What are access modifiers in Java?

Answer

Java has four access modifiers that control the visibility of classes, methods, and fields. private: accessible only within the same class. default (no modifier): accessible within the same package (package-private). protected: accessible within the same package and by subclasses in other packages. public: accessible from everywhere. The general best practice is to use the most restrictive modifier possible — private for fields (accessed via getters/setters), public only for the API that other classes need to use. This principle of least privilege is fundamental to encapsulation.