designwithfocus

Programming basics

What Is Encapsulation? Hiding State Behind Methods

By Design With Focus Team 6 min read
A class diagram with private fields behind public methods

Short answer

Encapsulation means an object keeps its state private and lets other code change that state only through methods. Oracle's Java tutorial calls that data encapsulation. Java enforces it with access modifiers such as private. Python does not have truly private fields. A leading underscore marks a non-public part of the API, and two leading underscores trigger name mangling.

Last verified against the sources listed below.

Key takeaways

  • Oracle defines data encapsulation as hiding state and requiring interaction through methods.
  • In Java, private members are visible only inside their own class. The tutorial says to prefer private.
  • Python's tutorial says truly private instance variables do not exist. A single underscore marks non-public API.
  • Two leading underscores in a class are mangled to _ClassName__name so subclasses do not clash.
  • Public fields, except constants, tie callers to one implementation. Oracle says to avoid them.
  • An object's methods are the API. Dev.java lists objects and the API as separate tutorial tracks.

What is encapsulation, in the Java tutorial’s words, is hiding an object’s internal state and requiring every interaction to go through its methods. Oracle’s object lesson calls that data encapsulation, and it calls the idea a fundamental principle of object-oriented programming.

The same lesson says a software object stores state in fields and exposes behavior through methods. Methods are how one object talks to another. Python draws the line differently, with a naming convention instead of a hard private keyword. Both versions are below, plus what that means for an API.

What problem does encapsulation solve?

It keeps the object in charge of its own data. Oracle’s bicycle stores current speed, pedal cadence, and gear, and it offers methods that change those values. If the bicycle has only 6 gears, the gear method can reject a number below 1 or above 6.

Without that method, any other code could set the gear to 0 or 99 and leave the object in a state the rest of the program never planned for. The check lives in one place. Callers do not each invent their own rule.

Oracle lists four results of bundling code into objects. Modularity means one object’s source can be maintained apart from the others, and information hiding means callers see methods, not the storage layout. Code re-use means you can call an object someone else already tested. Pluggability means you can swap a broken object for another with the same methods.

How does encapsulation work in Java?

Java uses access modifiers. Oracle’s access-control lesson lists two levels. A top-level class is public or package-private, which means no modifier. A member can be public, protected, package-private, or private.

private means the member can be accessed only in its own class. protected adds subclasses in other packages, and no modifier stops at the package. public is visible everywhere. The lesson’s table reads like this.

Modifier Class Package Subclass outside the package World
public Yes Yes Yes Yes
protected Yes Yes Yes No
no modifier Yes Yes No No
private Yes No No No

The tips on that page say to use the most restrictive level that makes sense, and to use private unless you have a good reason not to. They also say to avoid public fields except for constants, because a public field ties callers to one implementation.

How does encapsulation work in Python?

Python does not give you Java’s private keyword. The classes tutorial says private instance variables that cannot be reached from outside the object do not exist. Most code follows a convention instead. A name with one leading underscore, such as _spam, should be treated as a non-public part of the API.

Name mangling is the limited mechanism for class-private names. An identifier like __spam, with at least two leading underscores and at most one trailing underscore, is textually replaced with _classname__spam. The class name has its own leading underscores stripped. The point is to avoid clashes with names a subclass defines.

PEP 8 says to use one leading underscore only for non-public methods and instance variables. Use two leading underscores when you need mangling to avoid a subclass clash. Names with two leading and two trailing underscores, such as __init__, are the documented magic names. PEP 8 says not to invent new ones.

How does encapsulation work in an API?

The methods are the API. Oracle’s information-hiding benefit is exactly that: other code talks to methods, and the field layout can change later. Python’s tutorial says an underscored name is an implementation detail and can change without notice. That is the API contract, even though Python will not stop a caller who ignores it.

Dev.java lists Object Oriented-Programming under learning the language, and it lists a separate track called Mastering the API. The split matches the idea. The object owns the state. The API is the set of calls you publish.

A small component can follow the same shape. The SVG to JSX tool turns a drawing into one function that returns the markup. Callers use that function. They do not reassemble the SVG pieces themselves.

How do the two languages compare?

Java can refuse the access. Python asks you not to take it. The table is the practical difference when you are reading either language.

Question Java, from the tutorial Python, from the tutorial and PEP 8
Can outsiders read a hidden field? Not if it is private Yes, by convention they should not
Usual mark for hidden state private One leading underscore
Extra name protection The access modifier itself Two leading underscores, mangled
What callers should use Methods, or public constants The public names, not the underscored ones

Neither language’s docs promise a speed or bug-rate change from encapsulation. They describe control of state, and the freedom to change the inside later.

What mistakes break the hiding?

The common Java mistake is a public field that is not a constant. Oracle says those fields limit how you can change the code later. If every caller writes bike.gear = 7, you cannot add the 1-to-6 check without editing every caller.

The common Python mistake is treating _balance as a supported part of the API, or inventing a __dunder__ name. PEP 8 reserves the double-ended underscore form for names the language already documents. Mangling also does not hide the attribute from someone who writes _Foo__a.

Programming paradigms is the wider map for where objects sit.

Python is the language page if the underscore rules are the part you need next.

Frequently asked questions

What is encapsulation in Java?

In the Java tutorial, encapsulation is hiding an object's fields and making other code call methods to read or change them. The access-control lesson gives you private, protected, public, and package-private, which is no modifier. Private means the member is accessible only inside its own class. The tutorial's advice is to use the most restrictive level that still works, and to use private unless you have a good reason not to. Public fields are for constants, not for ordinary state.

How does encapsulation work in Python?

Python's class tutorial says private instance variables that only the object can touch do not exist. The convention is a single leading underscore, as in _spam, for a non-public part of the API. Two leading underscores, and at most one trailing underscore, turn on name mangling. Inside a class, __spam is rewritten as _ClassName__spam. That mainly stops a subclass from accidentally reusing the same name. PEP 8 says to use one underscore for non-public methods and instance variables.

How does encapsulation work in an API?

The methods you document are the API. Callers should use those methods and ignore the fields behind them. Oracle calls that information hiding: the internal implementation stays hidden, so you can change it without rewriting every caller. Python's tutorial uses the same idea when it says an underscored name is an implementation detail that can change without notice. Dev.java even splits its learning path into object-oriented programming and a separate track called Mastering the API.

Does a private field stop every kind of access?

In Java, the tutorial's access table says a private member is visible to its own class and not to the package, a subclass in another package, or the rest of the program. In Python, mangling is not a lock. PEP 8 notes that an insistent caller can still reach Foo._Foo__a. Treat that as a bypass, not as the supported API. If the language lets you reach the field, the design still asks you not to.

What is a good first method to hide state?

Oracle's bicycle example stores gear as state and exposes a method that changes it. If the bicycle has 6 gears, the method can reject a value below 1 or above 6. Callers never assign the gear field themselves. The same pattern works for a counter, a balance, or a list: keep the field private or underscored, and publish a method that checks the new value before it stores it.

Sources