Interview Q&A · Java · 6 questions in this topic

Access Modifiers for Classes, Methods and Variables — Java Interview Q&A

All Java topics

How the four access levels control visibility for classes, methods, and fields. Part of OOP Mechanics · 294 questions in the Java bank.

Which access modifiers are allowed on a top-level class?

Answer

Only public and package-private, written by omitting any modifier, are allowed on a top-level class. A public top-level class is visible everywhere, while a package-private class is visible only inside its own package. Adding private or protected is illegal, although non-access modifiers such as final, abstract, and sealed are permitted.

What are access modifiers in Java?

Answer

Access modifiers are keywords that enforce encapsulation by controlling where a class, method, constructor, or field can be used. Java has four access levels: private, package-private with no keyword, protected, and public, from most to least restrictive. Choosing the narrowest level that works keeps internals hidden and prevents misuse.

Key points

  1. 1private is visible only inside the same class.
  2. 2package-private is visible only inside the same package.
  3. 3protected adds subclasses in other packages, and public is visible everywhere.

Access specifiers vs access modifiers - is there a difference in Java?

Answer

In Java there is no separate category called access specifiers, so the Java Language Specification calls them all modifiers. Access modifiers are public, protected, private, and the default package-private level, while non-access modifiers include static, final, abstract, synchronized, and similar keywords. The specifier versus modifier split comes from C++, so it does not apply to Java.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits