Course contentsShow
← Java
Lesson 722 of 2,87017. Access Control in DepthFree lesson

Default to Most Restrictive: The Principle of Least Privilege

Learn why you should always start with private and only widen access when truly necessary to minimize coupling.

Default to Most Restrictive: The Principle of Least Privilege

What you'll learn: You'll understand why starting with private access and only widening when necessary creates better, more maintainable code.

The Core Principle

When you're designing a class, your first instinct might be to make everything public so it's "easy to use everywhere." But experienced developers do the opposite: they default to private for all members and only increase visibility when there's a clear, justified need.

This is called the Principle of Least Privilege—give each piece of code the minimum access rights it needs to do its job, nothing more.

Why Start with Private?

Think of your class like a smartphone. The internal circuits, battery management, and processor are all hidden inside. You only interact through carefully chosen interfaces: buttons, touchscreen, ports. If everything inside were exposed, you could accidentally damage it—and the manufacturer couldn't improve the internals without breaking your existing usage.

Similarly, private members:

  • Hide implementation details you might want to change later
  • Prevent accidental misuse by other classes
  • Reduce coupling between classes (they depend on less)
  • Make debugging easier (fewer places to check when things go wrong)

The Widening Process

Only widen access when you have a specific reason:

  • Need package access for testing or related classes? Use package-private (default).
  • Subclasses in other packages need access? Use protected.
  • External clients must access it? Use public.

Each step up exposes more of your internal design and makes future changes harder.

Key Takeaway: Always start with private access and only widen visibility when there's a compelling, documented reason—this minimizes coupling and maximizes your flexibility to change implementation details later.