Access Modifiers in Java — Java Technical Interview Questions & Answers

Access Modifiers in Java

Access Modifiers in Java

  • Access modifiers control who can see a class member. private: only the same class. default (no word): same package. protected: package + subclasses. public: everywhere.
  • Start strict (private) and open only when needed. Making everything public “for speed” breaks encapsulation.
  • Recite narrow to wide: private → default → protected → public. That sentence alone clears most MCQs.
  • Let's take this on the board with one tiny Main class — no extra files. Access Modifiers in Java — secret is private; outside code uses a getter. Start from main, go line by line, and stop at each print. That output is the proof for Access Modifiers.

Technical Interview Tip: Narrow → wide: private, default, protected, public.

Code Examples for Access Modifiers in Java

Example

// Same-file demo of access idea
class Box {
  private int secret = 7;
  int getSecret() { return secret; } // package/public API
}
public class Main {
  public static void main(String[] args) {
    System.out.println(new Box().getSecret());
  }
}

Access Modifiers in Java — secret is private; outside code uses a getter.

How to Explain Access Modifiers in Java to an Interviewer

Who can see a private member?

Only the same class

What is default access?

No modifier Same package

Who can see protected?

Same package Subclasses

Order from narrow to wide?

private default protected public