Java Access Modifiers: Private, Default, Protected and Public

Access modifiers (also known as access specifiers) determine the scope and visibility of classes, constructors, fields, and methods across package and subclass boundaries in Java.

The 4 Access Modifiers in Java

  • private: Accessible strictly within the declaring class only. Invisible to all other classes, even within the same package.
  • default (no keyword): Accessible to any class within the same package (package-private). Invisible outside the package.
  • protected: Accessible within the same package, and accessible to subclasses in external packages via inheritance.
  • public: Accessible from anywhere in the entire application or external modules.

Complete Visibility Comparison Matrix

Location of Access private default (none) protected public
Same Class YES YES YES YES
Same Package (Non-subclass) NO YES YES YES
Different Package (Subclass via inheritance) NO NO YES YES
Different Package (World / Non-subclass) NO NO NO YES

University Exam Corner (BCA / B.Sc CS)

Exam Question: "Can an overridden method reduce the visibility of the superclass method?"

Answer: No! An overriding method can maintain the same access or make it more accessible, but never more restrictive. For example, if a parent method is protected, the subclass can declare it protected or public. If you attempt to make it private or default, the compiler halts with: attempting to assign weaker access privileges.

Next Step

Now let us explore Abstraction and Abstract Classes. Proceed to: Java Abstraction & Abstract Classes →

Frequently Asked Questions (FAQ)

Q1. What is the Default access modifier in Java?
If you do not specify an access modifier (private, protected, or public), Java assigns 'default' (also known as package-private) visibility. The member is accessible to any class within the same package, but completely inaccessible outside that package.
Q2. What is the difference between protected and default access?
Default access allows visibility ONLY within the same package. Protected access allows visibility within the same package PLUS subclasses located in external packages via inheritance.
Q3. Can a top-level outer class be declared private or protected in Java?
No! A top-level outer class can only have 'public' or 'default' access. Only nested/inner classes can be declared private or protected.

Explore Related Java Tutorials

Accelerate your Java mastery by studying these tightly connected core tutorials:

Java Encapsulation →

Data hiding using private.

Java Packages →

Package boundaries and imports.

Java Inheritance →

Protected inheritance.

Abstraction in Java →

Abstract classes visibility.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!