Core Java · Chapter 12 of 48

Encapsulation

By the end of this chapter you can hide an object's fields behind methods that guard its rules, hand out copies instead of your own lists, and build an object that never changes. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Objects
  • 6 tasks
  • Java
  • In the all labs plan

The first 2 chapters of Core Java are free. This one comes with the all labs plan.

Why you need this

The CSMT counter's screen says it has -5 cups of masala chai left. Ravi wants it fixed: "You cannot sell chai you do not have." And Anjali needs a bill that never changes once printed: the customer holds the paper.

So far every field you wrote was open: any line in any file can write stock.cups = -5, and Java lets it. A constructor sets good values once, then nothing guards them, and finding the bug means reading every line that touches the field.

What you build: 6 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1 · interview question

    Interview: Stock.java, hide the fields behind getters

    In Stock.java, make all three fields of Stock private (item, cups and history), so only the class's own code can use them. Then make getItem() return the item's name and getCups() return the cups left.

    For example, new Stock("Masala chai", 20) gives Masala chai from getItem() and 20 from getCups().

  2. Task 2

    Stock.java: refuse a negative opening stock

    In Stock.java, make the constructor Stock(item, openingCups) throw an IllegalArgumentException when openingCups is negative, before it sets anything. An opening stock of 0 is allowed.

    For example, new Stock("Masala chai", -5) throws an IllegalArgumentException, and new Stock("Bun maska", 0) has 0 cups (the check reads them with getCups, from task 1).

  3. Task 3

    Stock.java: validate add and take

    In Stock.java, make add(amount) add delivered cups and take(amount) take sold cups off, each also recording a history line, "added N" or "took N". Both throw an IllegalArgumentException when amount is 0 or negative, and take also throws when amount is more than the cups left. A refused add or take leaves the cups as they were. Taking exactly what is left is fine and leaves 0.

    For example, a stock of 20 has 30 after add(10) and 25 after take(5). Then add(0), add(-3), take(0), take(-3) and take(26) all throw, and the stock still has 25. take(25) then leaves 0.

  4. Task 4

    Stock.java: hand out a copy of the history

    In Stock.java, make getHistory() return the history, oldest first, as a copy the caller cannot use to change the stock: never the history field itself. Clearing the returned list, or trying to when it cannot be changed, must leave the stock's own history as it was.

    For example, new Stock("Masala chai", 20).getHistory() is [opened with 20], and after a caller clears that list, getHistory() is still [opened with 20].

  5. Task 5

    Bill.java: make Bill immutable

    In Bill.java, make Bill immutable. The class is final, and its three fields (station, items and total) are private and final. The constructor Bill(station, items, total) keeps its own copy of items, so changing the caller's list afterwards does not change the bill. getItems() must not let anyone change the bill either: clearing the list it returns leaves the bill's items as they were.

    For example, a bill at SBC built from a list of Masala chai and Bun maska for 90 still has [Masala chai, Bun maska] after the caller adds Parle-G to their list, and after someone clears what getItems() returned. getStation() is SBC and getTotal() is 90.

  6. Task 6

    Bill.java: add an item by returning a new bill

    In Bill.java, make withItem(item, price) return a new Bill, never this one: the same station, this bill's items with item added at the end, and the total plus price. This bill must not change: it keeps its items and its total.

    For example, a bill at SBC of [Masala chai] for 40, after withItem("Bun maska", 50), returns a new bill at SBC of [Masala chai, Bun maska] for 90, and the old bill is still [Masala chai] for 40.

What you will learn

  • private: only the class's own code can use a field; everyone else goes through methods the class offers.
  • Methods that validate: refuse a bad value with an exception, before anything changes.
  • Defensive copies: never hand out, or keep, a list someone else also holds.
  • Immutable classes: objects that cannot change once built.

More in Objects

Build "Encapsulation" yourself

Tapri runs chai counters at railway stations, and every counter runs a Java program you write. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Core Java are free. This one comes with the all labs plan.