
Java OOP – Chapter 3: Encapsulation in Java
In this lesson, we’ll explore Encapsulation, one of the core pillars of Object-Oriented Programming. You’ll learn how to hide data, control access, and safely expose object behavior
What is Encapsulation?
Encapsulation is the process of wrapping data (fields) and code (methods) together in a single unit (a class), while restricting access to internal object details.
In Java, this is typically done by:
Declaring fields private.
Providing public getters and setters to access and modify those fields.
This helps protect the object’s internal state from external misuse.
Why Use Encapsulation?
Improves security – You control how data is modified.
Increases maintainability – You can change internal implementation without affecting outside code.
Simplifies debugging – Changes to a variable go through one controlled point.
Access Modifiers in Java
private: Within the same class only
default: Package-private (within the same package)
protected: Same package or subclasses
public: From anywhere
public class BankAccount {
public double balance; // Exposed directly
public void deposit(double amount) {
balance += amount;
}
}
// Anyone can do:
BankAccount b = new BankAccount();
b.balance = -5000; // Not safe!Example: With Encapsulation (GOOD)
public class BankAccount {
private double balance;
public void deposit(double amount) {
if (amount > 0) balance += amount;
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) balance -= amount;
}
public double getBalance() {
return balance;
}
}Summary
Encapsulation = hiding data + exposing safe interfaces (getters/setters).
Use private for fields and control access through public methods.
This protects object integrity and aligns with good design principles
Assignment: Lesson 3 – Encapsulation
Objective:
Practice encapsulating data in a class using private fields and public methods.
Part 1: Conceptual Questions
Write answers in a comment or separate file:
What is encapsulation and why is it important?
What keyword is used to make a field hidden from outside access?
Why shouldn’t we expose fields like
public int age;directly?
Part 2: Coding Task
Create a Person class with:
Private fields:
name(String),age(int)Public methods:
setName(String name)– sets the namesetAge(int age)– sets age if age ≥ 0getName()– returns the namegetAge()– returns the age
In your main() method:
Create a
PersonobjectSet name and age using the setter methods
Print the name and age using getters
Github: https://github.com/tuanbeovnn/java-bootcamp/tree/java-bootcamp-oop-chapter3
