0/30 Days Completed 0 Learning Days
Day 18 of 30 · Week 3 — OOPS Fundamentals
Encapsulation: private fields, getters, setters
1 Learn
Encapsulation means keeping an object's data safe inside it. Fields are made private so outside code cannot change them directly.
Public getter methods read the data; setter methods change it — and can check the value first.
2 See the Code
Java
class Account {
private double balance;
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
} else {
System.out.println("Invalid amount");
}
}
}
public class Bank {
public static void main(String[] args) {
Account acc = new Account();
acc.deposit(500);
acc.deposit(-50);
System.out.println(acc.getBalance());
}
}- balance is private — acc.balance = 1000000 would not compile outside the class.
- deposit() rejects negative amounts, protecting the data.
Output
Invalid amount 500.0
3 Practice
- Make a Student class with private marks, getMarks() and setMarks() that only accepts 0 to 100.
Try it in your own Java setup or write it in the Practice Notebook.
4 Quick Check
1. Encapsulation mainly protects...
2. Which access modifier hides a field from other classes?
Step 5
Answer and check the Quick Check above to unlock this.