Encapsulation OOP Basics – Visibility, Information Hiding, private, protected, public
This post is a definition of terms on encapsulation in OOP – including exam questions and tags.
In a Nutshell
Encapsulation hides the internal states and implementation details of an object, with only well-defined interfaces visible to the outside. The goal is robust, maintainable, and secure software through clear responsibility boundaries.
Concise Technical Description
Encapsulation is a central OOP principle that bundles data and behavior into a single unit and restricts direct access to internal representations. Technically, it is implemented through visibility modifiers such as private, protected, public, package, as well as through accessor methods and properties. Information hiding reduces coupling, increases cohesion, and allows implementation changes without affecting consumers. Invariants are maintained within the object, inputs and outputs are validated. Mutability is consciously controlled, immutable objects eliminate entire classes of errors.
Exam-Relevant Key Points
- Information hiding protects internal representation, reduces coupling
- Visibility modifiers private, protected, public, package control access
- Getters and setters are not an end in themselves, only provide when technically necessary
- IHK relevant, clearly distinguish terms encapsulation, abstraction, cohesion, coupling
- Immutable objects increase thread safety and testability in practice
- Validation, invariants, and the Law of Demeter prevent unsafe state manipulation
- Cost-effectiveness through lower maintenance costs and easier refactoring
- Documentation obligation, public interfaces, preconditions, postconditions
Core Components
- Language elements for visibility, private, protected, public, package
- Properties and methods, targeted exposure instead of complete disclosure
- Invariants, business rules that must always apply
- Contracts, preconditions and postconditions on the public API
- Mutability concept, mutable, immutable, copy on write
- Access control and validation, check inputs, atomic state changes
- Process step, refactoring to hide data fields and internal collections
- Architecture element, module boundaries, package boundaries, bounded contexts
- Security aspect, minimizing attack surface and injection points
- Test procedure, black box tests of the API and property-based tests for invariants
Practical Example
// Example, Java-like syntax
class BankAccount {
private String iban
private int balanceInCents
public BankAccount(String iban) {
if (iban == null) throw new IllegalArgumentException("IBAN required")
this.iban = iban
this.balanceInCents = 0
}
public int balance() {
return balanceInCents
}
public void deposit(int cents) {
if (cents <= 0) throw new IllegalArgumentException("positive amount")
balanceInCents += cents
}
public void withdraw(int cents) {
if (cents <= 0) throw new IllegalArgumentException("positive amount")
if (cents > balanceInCents) throw new IllegalStateException("overdraft not allowed")
balanceInCents -= cents
}
}
Explanation: Fields are private, only technically meaningful operations are public, invariants are checked.
Advantages and Disadvantages
Advantages
- Lower coupling, higher cohesion
- Better maintainability, easier parallelization
- Clear responsibilities, improved security through input controls
Disadvantages
- Possible overhead through boilerplate
- Overly strong encapsulation can hinder testability
- Excessive getter/setter inflation can undermine encapsulation
Typical Exam Questions (with Brief Answers)
-
Difference between encapsulation and abstraction? Encapsulation hides implementation details behind an interface, abstraction reduces visible complexity to relevant properties.
-
Visibility levels and usage? private only within the class, package only within the package, protected class and subclasses, public globally visible.
-
Public fields problematic? They bypass validation, violate invariants, increase coupling, and make refactoring risky.
-
Getters and setters worthwhile? When technical necessity exists, such as read access or controlled change with validation, otherwise avoid.
-
Immutability supports encapsulation? Immutable objects guarantee stable invariants, simplify concurrent use, and prevent side effects.
-
Law of Demeter and how it helps? Talk only to your direct neighbors, no chained access, reduces knowledge of internal structures, strengthens encapsulation.
-
Impact on test strategies? Focus on black box tests of the public API, internal details are verified through observable behavior.
-
Break encapsulation through collections? Returning an internal list enables external mutation, solution, defensive copy or unmodifiable view.
Most Important Sources
- https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
- https://de.wikipedia.org/wiki/Kapselung_(Programmierung)
- https://dl.acm.org/doi/10.1145/361598.361623