Encapsulation is the OOP principle that says an object should own its data and decide how that data is read or changed. Instead of leaving fields exposed for anyone to modify, you hide them behind a controlled interface of methods. The result is an object that can guarantee its own correctness — because every path into its state passes through code you wrote.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/Jhaymayleth/unidad2_java/llms.txt
Use this file to discover all available pages before exploring further.
What Encapsulation Means in Practice
Encapsulation has two complementary parts:- Bundling — fields (data) and the methods that act on them live together in the same class.
- Hiding — fields are
private; the outside world interacts only throughpublicmethods.
The Getter / Setter Pattern
The canonical Java pattern for encapsulation is:- Declare the field
private. - Provide a
publicgetter that returns the value. - Provide a
publicsetter that validates the incoming value before storing it.
emp.salario = -500; and the object would silently hold an invalid value.
The CuentaBancaria Example
The bank account class from Taller 7 is a textbook encapsulation example. It stores sensitive financial data in private fields and exposes only carefully validated operations:
numeroCuenta has a getter but no setter — the account number is set once at construction and never changes. That design decision is communicated purely through encapsulation.
depositar() and retirar()
Rather than allowing direct writes to saldo, CuentaBancaria exposes transactional methods that validate every operation:
transacciones counter automatically — something that would be impossible if saldo were a public field, because callers would bypass these methods entirely.
transferir() — Composing Encapsulated Operations
The transfer method reuses retirar() and depositar() rather than manipulating saldo directly. This means all validation rules are applied consistently, even inside the class itself:
Benefits of Encapsulation
Controlled Mutation
No field can be set to an invalid value — every write path goes through a method that validates first.
Invariant Enforcement
Constraints like “balance must be ≥ 0” or “account number is immutable” are guaranteed by the class itself.
Easier Refactoring
Rename a field, change its type, or restructure internal storage — callers never see the difference because they only call methods.