Access modifier

On this page 7

An access modifier is a language keyword that declares which parts of a program may see and use a class, field, method or constructor. In object-oriented programming, access modifiers such as public, private and protected are the primary mechanism that turns the design principle of encapsulation into rules the compiler or runtime actually enforces.

By restricting visibility, an access modifier separates a type’s stable public contract from its internal implementation details. Code outside that boundary cannot depend on hidden members, so the author can change them later without breaking callers, which is the main reason access control matters in large and long-lived codebases.

How access modifiers control visibility

An access modifier works by attaching a visibility level to a declaration, and the compiler checks every reference against that level. If code in one class tries to call a private method of another class, compilation fails in languages such as Java, C# and C++. The check happens at compile time in statically typed languages, so violations never reach production.

Visibility is evaluated relative to a scope of trust: the declaring class, its subclasses, its package or module, or the entire program. Each language defines these scopes slightly differently, which is why the same keyword can mean different things across ecosystems. The table below shows the common levels in their usual order from most to least restrictive.

LevelWho can accessTypical use
PrivateOnly the declaring classInternal state and helper methods
Package or internalCode in the same package or assemblyCollaborating classes in one component
ProtectedDeclaring class and its subclassesExtension points for inheritance
PublicAny code that can see the typeThe supported external API
Typical access levels from narrowest to widest

Access modifiers apply to members (fields, methods, constructors, nested types) and, in most languages, to top-level types as well. A private constructor, for example, prevents outside code from creating instances and is the standard building block of singletons and static factory methods.

Access modifiers across programming languages

Each mainstream language implements access modifiers with its own defaults and edge cases, and those differences are a frequent source of bugs when developers move between languages. The default level, applied when no keyword is written, is particularly important because it silently decides what becomes part of the API.

LanguageAvailable levelsDefault for class members
Javaprivate, package-private, protected, publicPackage-private
C#private, private protected, protected, internal, protected internal, publicPrivate
C++private, protected, publicPrivate in class, public in struct
Kotlinprivate, protected, internal, publicPublic
TypeScriptprivate, protected, public, plus #private fieldsPublic
PythonNo keywords, naming conventions onlyPublic by convention
Keywords and defaults in common languages

Java’s protected is notably wider than in C++, because it also grants access to every class in the same package. TypeScript’s private keyword is enforced only by the type checker and disappears in the emitted JavaScript, whereas the #field syntax gives true runtime privacy. Python relies on a leading underscore as a convention and on name mangling for double-underscore names, which discourages but does not prevent outside access.

Access modifiers, encapsulation and inheritance

Access modifiers are the enforcement tool, while encapsulation and abstraction are the design goals they serve. Encapsulation means bundling data with the methods that maintain its invariants; making fields private and exposing validated methods ensures that no outside code can put an object into an invalid state.

Inheritance introduces a second audience: subclasses. The protected level creates a semi-public contract with every future subclass, which is harder to change than it looks because the base class author cannot see all subclasses. When overriding, most languages forbid reducing visibility: a method that is public in the base class cannot become private in a subclass, since that would break polymorphism through the base type.

ConceptRelationship to access modifiersKey point
EncapsulationThe principle access modifiers enforceHides state behind methods
InterfaceMembers are implicitly public in most languagesDefines the external contract
InheritanceProtected members form the subclass contractVisibility cannot shrink on override
AbstractionPublic members expose only essential behaviorCallers see what, not how
How access modifiers relate to neighboring concepts

Choosing the right access level

The widely accepted rule is to start with the most restrictive level and widen it only when a concrete caller needs access. Every widening adds to the surface that must remain compatible, so visibility decisions are effectively API commitments.

DeclarationRecommended levelReason
Mutable field holding statePrivateProtects invariants
Helper method used by one classPrivateFree to change or remove
Class used only inside a modulePackage-private or internalKeeps it out of the public API
Hook intended for subclassesProtectedExplicit extension point
Operation required by external callersPublicPart of the documented contract
Constant shared widelyPublic and immutableSafe to expose read-only
Decision guide for common declarations

Library authors often go further by marking classes final or sealed and by using module systems, such as the Java Platform Module System, to hide whole packages. These tools complement access modifiers by controlling which types are exported, not only which members are visible.

Limitations and common mistakes

Access modifiers are a design and maintenance tool, not a security boundary. Reflection in Java and C#, pointer manipulation in C++ and plain attribute access in Python can all bypass them, so secrets and authorization checks must never rely on visibility alone.

  • Public mutable fields let any caller break invariants and make later refactoring impossible without breaking changes.
  • Overusing protected exposes internals to unknown subclasses and creates the fragile base class problem.
  • Widening visibility for unit tests leaks test needs into the production API; testing through public behavior is usually better.
  • Relying on defaults without knowing them, such as Kotlin’s public default, accidentally publishes members.
  • Getters and setters for every field technically keep fields private but expose the same internals through methods.

A subtle point is that in Java, C# and C++, private is class-scoped, not object-scoped: one instance can read the private fields of another instance of the same class. This behavior is intentional and makes methods such as equals straightforward to implement.

A plain-language summary

Think of a restaurant. Guests see the menu and the dining room, staff can enter the kitchen, and only the owner opens the safe. Access modifiers draw these same lines inside software, deciding which parts of a program are open to everyone and which are kept behind the counter.

This matters because the hidden parts can be rearranged freely without upsetting anyone who relies on the visible parts. The key idea is simple: show only what others truly need, and keep everything else private.

An example from practice

A development team maintains a Java payment library used by about 40 internal services. Its Invoice class originally exposed a public List of line items, and several services modified that list directly, which occasionally produced invoices whose stored total no longer matched their lines.

During a refactoring, the team made the list private, added a public addLine method that recalculates the total on every change, and returned only an unmodifiable view from the getter. Helper classes for tax calculation were moved to package-private visibility so they disappeared from the public API.

The compiler immediately flagged 17 call sites that had modified the list directly, and each was changed to the new method. The outcome was zero mismatched totals in the following quarter, and the team later replaced the internal tax logic twice without any consuming service needing a code change.