Java OOP
Encapsulation
Complete lesson for Encapsulation using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Encapsulation
Section: Java OOP. Java encapsulation — wrap data and methods in one class, hide fields with private, expose safe getters, setters, and behaviour methods, with real-life examples (capsule, ATM, car, smartphone), validation, immutability, and defensive copies.
What is encapsulation?
- Encapsulation means wrapping data (fields) and the code that works on that data (methods) together into a single unit, the class.
- It also means hiding the data: fields are made
private, and outside code can reach them only throughpublicmethods that apply rules. - So callers say what they want (
deposit(500)), and the class decides how and whether it is allowed. - Real-life example: a medicine capsule. The shell wraps the medicine inside. You swallow the capsule; you never touch or measure the powder yourself.
public class BankAccount {
private double balance; // hidden data
public BankAccount(double opening) {
if (opening < 0) throw new IllegalArgumentException("opening balance cannot be negative");
this.balance = opening;
}
public double getBalance() { // controlled read
return balance;
}
public void deposit(double amount) { // controlled write with a rule
if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
balance += amount;
}
public static void main(String[] args) {
BankAccount acc = new BankAccount(1000);
acc.deposit(500);
System.out.println(acc.getBalance()); // 1500.0
// acc.balance = -500; // compile error: balance has private access
}
} Encapsulation in real life — hide the inside, expose safe controls
A capsule hides its medicine, an ATM hides its cash vault, a car hides its engine, and a phone hides its circuit board. Each gives you only safe controls. A Java class does the same with private fields and public methods.
- Hide: declare fields
privateso no outside code can set invalid values. - Expose: provide
publicgetters, setters, or behaviour methods likedeposit(). - Validate: check rules in constructors and setters before changing state.
- Result:
acc.balance = -500;fails to compile;acc.deposit(500)is the only way in.
Real-life examples of encapsulation
- In every example, the inside is protected and you use only the safe controls on the outside.
| Real-life object | Hidden inside (private data) | Safe controls outside (public methods) | Java idea |
|---|---|---|---|
| Medicine capsule | Medicine powder and dose | Swallow the capsule | Class wraps data and methods |
| ATM machine | Cash vault, bank balance | Card, PIN, withdraw and balance buttons | withdraw(amount), getBalance() |
| Car | Engine, fuel injection, wiring | Steering, accelerator, brake | drive(), brake() |
| Smartphone | Circuit board, battery, OS files | Touch screen, buttons, settings app | Public interface, private internals |
| TV remote | Circuit and infrared signal codes | Power, volume, channel buttons | volumeUp() instead of setting voltage |
| Bank locker | Jewellery and documents | Key plus bank verification | Access only through checked methods |
| Vending machine | Stock count, coin box | Select item, insert money | buy(code, money) validates both |
| Washing machine | Motor speed, water valves | Programme knob and start button | start(Programme.COTTON) |
| Company payroll | Employee salary details | HR portal with login | getSalary() only for authorised users |
| School report card | Marks register | Printed report with grades | Read-only getter, no setter |
Why we need encapsulation
- Data protection: nobody can set
age = -5orbalance = -1000directly. - Validation in one place: rules live in the setter or constructor, not scattered across the program.
- Flexibility: you can change how data is stored (for example rupees to paise, Celsius to Kelvin) without breaking any caller.
- Read-only or write-only control: decide per field whether outsiders may read it, change it, or neither.
- Easier debugging and testing: every change to a field passes through a method you can log or breakpoint.
- Real-life example: a bank never lets customers walk into the vault and update their own balance. Every change goes through a counter or ATM that checks the rules.
How to achieve encapsulation in Java
- Step 1: Declare every field
private. - Step 2: Provide
publicgetter methods only for fields others may read. - Step 3: Provide
publicsetter methods only for fields others may change, and validate inside them. - Step 4: Validate in the constructor too, so an object is never created with bad data.
- Step 5: Prefer meaningful behaviour methods (
deposit,withdraw,promote) over raw setters when the change has business rules.
public class Student {
private String name; // Step 1: private fields
private int age;
private double marks;
public Student(String name, int age, double marks) { // Step 4: validate at creation
setName(name);
setAge(age);
setMarks(marks);
}
public String getName() { return name; } // Step 2: getters
public int getAge() { return age; }
public double getMarks(){ return marks; }
public void setName(String name) { // Step 3: validating setters
if (name == null || name.isBlank()) throw new IllegalArgumentException("name required");
this.name = name.trim();
}
public void setAge(int age) {
if (age < 3 || age > 100) throw new IllegalArgumentException("age must be 3-100");
this.age = age;
}
public void setMarks(double marks) {
if (marks < 0 || marks > 100) throw new IllegalArgumentException("marks must be 0-100");
this.marks = marks;
}
public char getGrade() { // Step 5: behaviour, not raw data
return marks >= 90 ? 'A' : marks >= 75 ? 'B' : marks >= 60 ? 'C' : 'D';
}
} Without encapsulation vs with encapsulation
- With public fields, any line of code anywhere can put the object into an impossible state, and the compiler cannot stop it.
- With private fields and validating methods, the bad value is rejected at the door.
// WITHOUT encapsulation
class Person1 {
public int age;
}
// WITH encapsulation
class Person2 {
private int age;
public int getAge() { return age; }
public void setAge(int age) {
if (age < 0 || age > 130) {
System.out.println("Rejected invalid age: " + age);
return;
}
this.age = age;
}
}
public class CompareDemo {
public static void main(String[] args) {
Person1 p1 = new Person1();
p1.age = -25; // accepted silently: object is now invalid
System.out.println(p1.age); // -25
Person2 p2 = new Person2();
p2.setAge(-25); // Rejected invalid age: -25
p2.setAge(25);
System.out.println(p2.getAge()); // 25
}
} Getter and setter naming rules
- These names follow the JavaBeans convention, which IDEs, Spring, Hibernate, Jackson, and JSP all rely on.
- Generate them in IntelliJ / Eclipse with Alt+Insert or Source > Generate Getters and Setters, then add validation.
| Field | Getter (accessor) | Setter (mutator) | Note |
|---|---|---|---|
private String name; | public String getName() | public void setName(String name) | Capitalize the first letter after get / set |
private int age; | public int getAge() | public void setAge(int age) | Validate range in the setter |
private boolean active; | public boolean isActive() | public void setActive(boolean active) | Booleans use is instead of get |
private double salary; | public double getSalary() | public void setSalary(double salary) | Often no setter; use raiseSalary(percent) |
private List<String> skills; | public List<String> getSkills() | public void addSkill(String s) | Return a copy; add / remove methods instead of a setter |
private final String id; | public String getId() | none | final fields get only a getter |
Read-only, write-only, and read-write classes
| Type | Methods provided | Real-life example | Java example |
|---|---|---|---|
| Read-only | Getters only (fields set in constructor) | Printed report card: you can read, not change marks | getMarks() only |
| Write-only | Setters only | Ballot box or suggestion box: you put in, cannot read others | setPassword() with no getter |
| Read-write | Getters and setters | Your phone contact list: view and edit | getPhone(), setPhone() |
| Fully hidden | Neither; only behaviour methods | ATM cash vault | withdraw() but no getVault() |
class ReportCard { // read-only
private final String student;
private final int marks;
ReportCard(String student, int marks) { this.student = student; this.marks = marks; }
public String getStudent() { return student; }
public int getMarks() { return marks; }
}
class Login { // write-only password
private String passwordHash;
public void setPassword(String raw) {
if (raw.length() < 8) throw new IllegalArgumentException("min 8 characters");
this.passwordHash = Integer.toHexString(raw.hashCode()); // demo only, use a real hash in production
}
public boolean check(String raw) {
return passwordHash != null && passwordHash.equals(Integer.toHexString(raw.hashCode()));
}
} Access modifiers used for encapsulation
- Encapsulation is the design goal; access modifiers are the tools Java gives you to achieve it.
| Modifier | Same class | Same package | Subclass (other package) | Everywhere | Typical use |
|---|---|---|---|---|---|
private | Yes | No | No | No | Fields and helper methods |
| default (no modifier) | Yes | Yes | No | No | Package-internal helper classes |
protected | Yes | Yes | Yes | No | Hooks meant for subclasses |
public | Yes | Yes | Yes | Yes | The class API: constructors, getters, behaviour |
Differences between encapsulation, data hiding, and abstraction
| Point | Encapsulation | Data hiding | Abstraction |
|---|---|---|---|
| Meaning | Wrap data and methods together in a class | Make data inaccessible from outside | Show only essential features, hide complexity |
| Focus | How the class is packaged | Who can access the data | What the user needs to know |
| Achieved with | Class + private fields + public methods | private (and other access modifiers) | abstract classes and interfaces |
| Level | Implementation level | Implementation level | Design level |
| Question it answers | "How is it bundled and protected?" | "Can outsiders see it?" | "What can it do?" |
| Real-life example | Capsule shell holding medicine | You cannot see inside the capsule | You only know "take one after food" |
| Car example | Engine and controls in one car body | Engine is under a locked bonnet | You only know steering, accelerator, brake |
Public fields vs getters and setters
| Exposure | Risk | Better choice |
|---|---|---|
public int age; | Anyone can set -3; no way to add rules later | private field + validating setter |
| Getter and setter with no checks | Almost the same as a public field | Add validation, or remove the setter |
| Getter only | Safe for primitives and immutable types | Good default for most fields |
Getter returning an internal List / array | Caller can change your data through it | Return List.copyOf(...) or a clone |
Setter for a computed value (setTotal) | Value can disagree with its parts | Compute in a getter (getTotal()) |
record / all final fields | No accidental change | Use for pure data carriers |
Advanced — Encapsulation
Defensive copies: do not leak mutable internals
- A
privatefield is not safe if a getter returns the actualList, array, orDateobject. The caller can change it through that reference. - Copy mutable inputs in the constructor and copy (or wrap as unmodifiable) on the way out.
- Real-life example: a library gives you a photocopy of the rare book page, not the original book, so scribbles cannot damage the original.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Team {
private final List<String> members = new ArrayList<>();
private final int[] scores;
public Team(int[] scores) {
this.scores = scores.clone(); // copy on the way in
}
public void addMember(String name) {
if (name == null || name.isBlank()) throw new IllegalArgumentException("name required");
members.add(name);
}
public List<String> getMembers() { return List.copyOf(members); } // read-only copy
public int[] getScores() { return scores.clone(); } // copy on the way out
public static void main(String[] args) {
int[] input = {10, 20};
Team t = new Team(input);
input[0] = 999; // does not affect Team
t.addMember("Asha");
try {
t.getMembers().add("Hacker");
} catch (UnsupportedOperationException e) {
System.out.println("Cannot modify team from outside");
}
System.out.println(t.getMembers() + " " + Arrays.toString(t.getScores())); // [Asha] [10, 20]
}
} Immutable classes: the strongest encapsulation
- Make the class
final, all fieldsprivate final, set them only in the constructor, provide no setters, and copy mutable inputs and outputs. - Operations return a new object instead of changing the current one, like
String.toUpperCase()andLocalDate.plusDays(). - Immutable objects are automatically thread-safe and safe to use as
HashMapkeys. - Real-life example: a printed currency note. Its value is fixed; to "change" 500 into two 200s and a 100 you get new notes.
public final class Money {
private final long paise; // stored as paise to avoid floating-point errors
public Money(long rupees, int paise) {
if (rupees < 0 || paise < 0 || paise > 99) throw new IllegalArgumentException("invalid amount");
this.paise = rupees * 100 + paise;
}
private Money(long totalPaise) { this.paise = totalPaise; }
public Money plus(Money other) { return new Money(this.paise + other.paise); } // new object
@Override
public String toString() { return "Rs." + (paise / 100) + "." + String.format("%02d", paise % 100); }
public static void main(String[] args) {
Money a = new Money(199, 50);
Money b = new Money(100, 75);
Money total = a.plus(b);
System.out.println(a + " + " + b + " = " + total); // Rs.199.50 + Rs.100.75 = Rs.300.25
}
} Tell, do not ask: behaviour methods instead of raw setters
- A setter like
setBalance(5000)lets callers bypass business rules (daily limits, minimum balance, audit logs). - Expose intention-revealing methods (
deposit,withdraw,transfer) and let the object enforce its own rules. - Real-life example: you tell the ATM "withdraw 2000"; you do not ask it for the vault key and count notes yourself.
public class Atm {
private double balance;
private double withdrawnToday;
private static final double DAILY_LIMIT = 20000;
private final int pin;
public Atm(int pin, double opening) { this.pin = pin; this.balance = opening; }
public boolean withdraw(int enteredPin, double amount) {
if (enteredPin != pin) { System.out.println("Wrong PIN"); return false; }
if (amount <= 0 || amount % 100 != 0) { System.out.println("Enter multiples of 100"); return false; }
if (amount > balance) { System.out.println("Insufficient balance"); return false; }
if (withdrawnToday + amount > DAILY_LIMIT) { System.out.println("Daily limit reached"); return false; }
balance -= amount;
withdrawnToday += amount;
System.out.println("Please collect Rs." + amount);
return true;
}
public double getBalance(int enteredPin) {
if (enteredPin != pin) throw new SecurityException("Wrong PIN");
return balance;
}
public static void main(String[] args) {
Atm atm = new Atm(4321, 30000);
atm.withdraw(1111, 500); // Wrong PIN
atm.withdraw(4321, 550); // Enter multiples of 100
atm.withdraw(4321, 15000); // Please collect Rs.15000.0
atm.withdraw(4321, 6000); // Daily limit reached
System.out.println(atm.getBalance(4321)); // 15000.0
}
} Changing the internal representation safely
- Because callers use only methods, you can change how data is stored without touching any caller.
- Here the class stores Kelvin internally but still offers Celsius and Fahrenheit methods.
public class Temperature {
private double kelvin; // internal choice, hidden
public void setCelsius(double c) {
if (c < -273.15) throw new IllegalArgumentException("below absolute zero");
kelvin = c + 273.15;
}
public double getCelsius() { return kelvin - 273.15; }
public double getFahrenheit() { return getCelsius() * 9 / 5 + 32; }
public static void main(String[] args) {
Temperature t = new Temperature();
t.setCelsius(37);
System.out.printf("%.1f C = %.1f F%n", t.getCelsius(), t.getFahrenheit()); // 37.0 C = 98.6 F
}
} JavaBeans, records, and frameworks
- A JavaBean is a class with a public no-arg constructor, private fields, and getters / setters. Spring, Hibernate (JPA), Jackson, and JSP use these methods to read and write properties.
- A
recordencapsulates storage (fields areprivate final) but exposes every component through an accessor. Use it for transparent data carriers such as DTOs. - Use a normal class when you need rules, hidden state, or controlled changes.
// JavaBean style (frameworks call the getters / setters)
public class CustomerBean implements java.io.Serializable {
private String name;
private String email;
public CustomerBean() { }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) {
if (email == null || !email.contains("@")) throw new IllegalArgumentException("invalid email");
this.email = email;
}
}
// Record style (immutable data carrier)
record CustomerDto(String name, String email) { } Encapsulation beyond classes: packages and modules
- Package-private (no modifier) hides whole helper classes from other packages; only the public API class is visible.
- Java 9 modules go further: even
publicclasses are hidden unless their package is listed inexports. - Reflection with
setAccessible(true)can read private fields in the classpath world, but modules block it unless the package isopens. Never rely on reflection to bypass encapsulation in application code.
Encapsulation and thread safety
- When all access to a field goes through the class methods, you can add
synchronized(or useAtomicInteger) in one place and the whole program becomes safe. - With a public field, every caller would have to remember to lock, which never works in practice.
import java.util.concurrent.atomic.AtomicInteger;
public class VisitorCounter {
private final AtomicInteger count = new AtomicInteger();
public int arrive() { return count.incrementAndGet(); } // thread-safe, hidden detail
public int current() { return count.get(); }
} Tricky Interview Points
Q1) What is encapsulation in Java?
Answer Wrapping data (fields) and the methods that operate on it into one class, and restricting direct access to the data with private fields and public methods that enforce rules.
Q2) Give a real-life example of encapsulation.
Answer An ATM: the cash vault and your balance are hidden, and you can only use the card, PIN, and buttons (public methods) which check the rules. A medicine capsule and a car (engine hidden, steering and brake exposed) are other examples.
Q3) How do you achieve encapsulation in Java?
Answer Declare fields private, provide public getters and setters (or behaviour methods) only where needed, and validate data in setters and constructors.
Q4) What are the advantages of encapsulation?
Answer Data protection, validation in one place, freedom to change internal representation, read-only or write-only control, easier debugging and testing, and simpler thread safety.
Q5) Encapsulation vs data hiding?
Answer Data hiding is restricting access to data with private. Encapsulation is the broader idea of bundling data with methods and controlling access; data hiding is one part of it.
Q6) Encapsulation vs abstraction?
Answer Encapsulation hides the data and implementation inside a class (how). Abstraction hides complexity and shows only essential operations, using abstract classes and interfaces (what).
Q7) Why not just use public fields?
Answer You cannot validate, log, synchronize, or change the representation later without breaking every caller.
Q8) Is a class with getters and setters for every field encapsulated?
Answer Only weakly. Setters without validation are nearly public fields. Good encapsulation exposes only what is needed and prefers behaviour methods such as deposit and withdraw.
Q9) What is a read-only class? A write-only class?
Answer A read-only class has only getters (values set in the constructor). A write-only class has only setters, for example a password that can be set but never read back.
Q10) What are the naming rules for getters and setters?
Answer getXxx and setXxx for most fields, and isXxx for boolean getters, following the JavaBeans convention.
Q11) How do you encapsulate a List field?
Answer Keep it private, never return the original list; return List.copyOf or Collections.unmodifiableList, and provide addItem / removeItem methods with validation.
Q12) What is a defensive copy?
Answer Copying a mutable object (array, list, Date) when it enters or leaves your class so outside code cannot change your internal state through a shared reference.
Q13) How do you create an immutable class?
Answer Make the class final, all fields private final, assign them only in the constructor, provide no setters, and make defensive copies of mutable fields.
Q14) Can private fields be accessed from outside?
Answer Not by normal code. Reflection with setAccessible(true) can on the classpath, but modules block it unless the package is opened. It should not be used to break encapsulation.
Q15) What is a JavaBean?
Answer A class with a public no-arg constructor, private fields, and public getters and setters, often Serializable. Frameworks use it to read and write properties automatically.
Q16) Which OOP principle does a record represent?
Answer A record is an immutable, transparent data carrier: storage is encapsulated in private final fields, but every component is readable through an accessor.
Q17) Is encapsulation possible without getters and setters?
Answer Yes. Behaviour methods (deposit, withdraw, ship) can be the only way to change state, and some state may never be exposed at all.
Simple Programs
Employee with validated salary and a raise method
public class Employee {
private final int id;
private String name;
private double salary;
public Employee(int id, String name, double salary) {
if (salary < 10000) throw new IllegalArgumentException("salary below minimum wage");
this.id = id;
this.name = name;
this.salary = salary;
}
public int getId() { return id; }
public String getName() { return name; }
public double getSalary() { return salary; }
public void raise(double percent) {
if (percent <= 0 || percent > 50) {
System.out.println("Raise must be between 0 and 50 percent");
return;
}
salary += salary * percent / 100;
}
public static void main(String[] args) {
Employee e = new Employee(501, "Meena", 40000);
e.raise(10);
e.raise(80); // Raise must be between 0 and 50 percent
System.out.println(e.getName() + " earns Rs." + e.getSalary()); // Meena earns Rs.44000.0
}
} Student result: computed grade, no setter for grade
public class Result {
private final String name;
private final int[] marks;
public Result(String name, int... marks) {
for (int m : marks) {
if (m < 0 || m > 100) throw new IllegalArgumentException("mark out of range: " + m);
}
this.name = name;
this.marks = marks.clone();
}
public double getAverage() {
int sum = 0;
for (int m : marks) sum += m;
return marks.length == 0 ? 0 : (double) sum / marks.length;
}
public String getGrade() { // always consistent with marks
double avg = getAverage();
return avg >= 90 ? "A" : avg >= 75 ? "B" : avg >= 60 ? "C" : "D";
}
public static void main(String[] args) {
Result r = new Result("Asha", 92, 85, 78);
System.out.printf("%s: %.2f (%s)%n", r.name, r.getAverage(), r.getGrade()); // Asha: 85.00 (B)
}
} Vending machine: hidden stock and coin box
import java.util.HashMap;
import java.util.Map;
public class VendingMachine {
private final Map<String, Integer> stock = new HashMap<>();
private final Map<String, Integer> price = new HashMap<>();
private int coinBox;
public VendingMachine() {
stock.put("A1", 2); price.put("A1", 20); // chips
stock.put("B1", 1); price.put("B1", 40); // juice
}
public String buy(String code, int money) {
if (!stock.containsKey(code)) return "Invalid code";
if (stock.get(code) == 0) return "Sold out";
int cost = price.get(code);
if (money < cost) return "Insert Rs." + (cost - money) + " more";
stock.put(code, stock.get(code) - 1);
coinBox += cost;
return "Enjoy! Change: Rs." + (money - cost);
}
public static void main(String[] args) {
VendingMachine vm = new VendingMachine();
System.out.println(vm.buy("B1", 30)); // Insert Rs.10 more
System.out.println(vm.buy("B1", 50)); // Enjoy! Change: Rs.10
System.out.println(vm.buy("B1", 50)); // Sold out
System.out.println(vm.buy("Z9", 50)); // Invalid code
}
} Shopping cart with an unmodifiable item list
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Cart {
private final List<String> items = new ArrayList<>();
private double total;
public void add(String item, double price, int qty) {
if (qty <= 0 || price < 0) throw new IllegalArgumentException("invalid quantity or price");
for (int i = 0; i < qty; i++) items.add(item);
total += price * qty;
}
public List<String> getItems() { return Collections.unmodifiableList(items); }
public double getTotal() { return total; }
public static void main(String[] args) {
Cart c = new Cart();
c.add("Pen", 20, 3);
c.add("Notebook", 55, 2);
System.out.println(c.getItems() + " = Rs." + c.getTotal());
try {
c.getItems().clear();
} catch (UnsupportedOperationException e) {
System.out.println("Cart contents are protected");
}
}
} Mobile phone: private battery with public controls
public class Phone {
private int battery = 100; // hidden
private boolean on;
public void powerOn() { if (battery > 0) on = true; }
public void powerOff() { on = false; }
public void watchVideo(int minutes) {
if (!on) { System.out.println("Switch the phone on first"); return; }
battery = Math.max(0, battery - minutes / 2);
if (battery == 0) { on = false; System.out.println("Battery empty, phone switched off"); }
}
public void charge(int minutes) { battery = Math.min(100, battery + minutes); }
public int getBattery() { return battery; }
public static void main(String[] args) {
Phone p = new Phone();
p.watchVideo(30); // Switch the phone on first
p.powerOn();
p.watchVideo(60);
System.out.println(p.getBattery() + "%"); // 70%
p.charge(50);
System.out.println(p.getBattery() + "%"); // 100%
}
} Immutable Address with a "with" method
public final class Address {
private final String city;
private final String pin;
public Address(String city, String pin) {
if (!pin.matches("\\d{6}")) throw new IllegalArgumentException("PIN must be 6 digits");
this.city = city;
this.pin = pin;
}
public String getCity() { return city; }
public String getPin() { return pin; }
public Address withCity(String newCity) { return new Address(newCity, pin); } // new object
@Override
public String toString() { return city + " - " + pin; }
public static void main(String[] args) {
Address home = new Address("Hyderabad", "500016");
Address moved = home.withCity("Secunderabad");
System.out.println(home); // Hyderabad - 500016 (unchanged)
System.out.println(moved); // Secunderabad - 500016
}
} Library book: issue and return with rules
public class LibraryBook {
private final String title;
private String issuedTo; // null means available
public LibraryBook(String title) { this.title = title; }
public boolean issue(String member) {
if (issuedTo != null) {
System.out.println(title + " is already issued to " + issuedTo);
return false;
}
issuedTo = member;
System.out.println(title + " issued to " + member);
return true;
}
public void giveBack(String member) {
if (!member.equals(issuedTo)) {
System.out.println(member + " did not borrow " + title);
return;
}
issuedTo = null;
System.out.println(title + " returned by " + member);
}
public boolean isAvailable() { return issuedTo == null; }
public static void main(String[] args) {
LibraryBook b = new LibraryBook("Effective Java");
b.issue("Asha");
b.issue("Ravi"); // already issued to Asha
b.giveBack("Ravi"); // Ravi did not borrow
b.giveBack("Asha");
System.out.println(b.isAvailable()); // true
}
} Problem Solving Tricks
- Golden rule: fields
private, behaviourpublic. - Think "capsule": data and methods inside one shell, only safe controls outside.
- Validate in the constructor and in every method that changes state.
- Do not auto-generate a setter for every field; ask "should outsiders really change this?"
- Use
isfor boolean getters:isActive(), notgetActive(). - Prefer verbs (
deposit,promote,issue) oversetBalance,setRole,setStatuswhen rules apply. - Never return an internal
List, array, orDatedirectly; return a copy or an unmodifiable view. - Computed values (total, grade, age from date of birth) need a getter, not a setter.
- For pure data with no rules, a
recordis shorter and safer than a hand-written bean. - Package-private is encapsulation too: hide helper classes that are not part of your API.
Practice Programs List
- Convert a
Personclass with public fields into private fields with getters and validating setters. - Write a
BankAccountwithdeposit,withdraw, andgetBalance, enforcing that the balance never goes negative. - Write an
Atmclass with a PIN check, multiples of 100, and a daily withdrawal limit. - Create a read-only
ReportCardclass (getters only) and a write-onlyLoginclass (password setter only). - Add an
isActive()boolean getter andsetActive()setter to aUserclass. - Write a
Temperatureclass that stores Kelvin internally but offers Celsius and Fahrenheit methods. - Break encapsulation on purpose by returning an internal
List, show the problem, then fix it withList.copyOf. - Create a class that takes an
int[]in its constructor and prove that changing the original array does not affect it. - Write an immutable
MoneyorFractionclass withplusreturning a new object. - Model a vending machine with hidden stock and a
buy(code, money)method. - Model a phone with a private battery level and public
chargeandwatchVideomethods. - Write a table of five real-life objects with their hidden parts and public controls, then code one of them.
- Compare encapsulation, data hiding, and abstraction for a car in your own words and code.
- Rewrite a simple
CustomerJavaBean as arecordand list what changes.