Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › OOP III — Encapsulation, Abstraction, Enums

How do access modifiers (private, package-private, protected, public) shape API design, and what's the danger of protected?

Level II · JuniorOOP III — Encapsulation, Abstraction, Enums
Answer

The discipline is to default to the most restrictive modifier and widen only when needed, because every public or protected member becomes a contract you must support. package-private is underused but excellent for collaborating classes that shouldn't expose internals to the world. protected is the subtle one: it's part of the inheritance contract, so a protected field becomes a commitment to every future subclass author and ties your hands when refactoring — prefer protected methods over protected fields.

Common mistakes
  • Making everything public by default.
  • Forgetting that protected also grants package access.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for OOP III — Encapsulation, Abstraction, Enums.

Practise free

More on OOP III — Encapsulation, Abstraction, Enums