Read-only fields and computed values
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A read-only field can be read from outside but never changed: it gets a value in the constructor, has a getter, and has no setter. A computed value is not stored at all; a getter works it out from other fields each time it is asked.
Read-only means a getter and no setter
A train ticket's PNR must never change once it is printed. Make it read-only: set it in the constructor, give a getter, and write no setter or other method that changes it.
Example 1 · A read-only train ticket
class Ticket { private String pnr; private String from; private String to;
public Ticket(String pnr, String from, String to) { this.pnr = pnr; this.from = from; this.to = to; }
public String getPnr() { return pnr; } public String getFrom() { return from; } public String getTo() { return to; }}
public class TicketDemo { public static void main(String[] args) { Ticket t = new Ticket("4521367890", "Chennai", "Bengaluru"); System.out.println("PNR " + t.getPnr() + ": " + t.getFrom() + " to " + t.getTo()); }}PNR 4521367890: Chennai to Bengaluru
What this code does
- All three values are set once in the constructor. There are only getters, so nothing can change them later.
- The class decides that a printed ticket is fixed, just like a real one.
Three kinds of field, by what outside code may do:
- Read-write: getter + setter (a phone number).
- Read-only: getter only (a roll number); the class itself guarantees it stays the same.
- Hidden: neither (a PIN).
Compute, don’t store
A cart shows 3 items but a total of Rs. 500. A stored total must be updated every time a field it depends on changes; forget once and it is stale (out of date).
Example 2 · A stored total goes stale
class CartItem { private int price; private int quantity; private int total;
public CartItem(int price, int quantity) { this.price = price; this.quantity = quantity; this.total = price * quantity; }
public void setQuantity(int quantity) { this.quantity = quantity; // forgot to update total }
public int getQuantity() { return quantity; } public int getTotal() { return total; }}
public class StaleDemo { public static void main(String[] args) { CartItem c = new CartItem(250, 2); c.setQuantity(3); System.out.println(c.getQuantity() + " items, total Rs. " + c.getTotal()); }}3 items, total Rs. 500
What this code does
totalwas stored once in the constructor.setQuantitychangedquantitybut nottotal.- Now the object disagrees with itself: 3 items at Rs. 250 should be Rs. 750.
Example 3 · Computed getters are never out of date
class ReportCard { private String name; private int physics; private int chemistry; private int maths;
public ReportCard(String name, int physics, int chemistry, int maths) { this.name = name; this.physics = physics; this.chemistry = chemistry; this.maths = maths; }
public int getTotal() { return physics + chemistry + maths; }
public double getPercentage() { return getTotal() * 100.0 / 300; }
public boolean isPass() { return physics >= 35 && chemistry >= 35 && maths >= 35; }
public String getName() { return name; }}
public class ComputedDemo { public static void main(String[] args) { ReportCard r = new ReportCard("Priya", 82, 74, 90); System.out.println(r.getName() + ": " + r.getTotal() + "/300, " + r.getPercentage() + "%, pass: " + r.isPass()); }}Priya: 246/300, 82.0%, pass: true
What this code does
- There is no
totalfield.getTotal()adds the marks every time, so it always matches them. getPercentage()uses100.0so the division is done indouble. With100it would beintdivision.
A computed getter like getTotal() works the answer out each time it is called, so it can never be stale, and there is no setter to misuse. To the caller it looks like any other getter.
A private array is shared through its reference
getMarks() returns a private array, and main changes a mark with no setter. An array variable holds a reference, as in Arrays and methods (opens in a new tab), so return marks; hands out your array itself, not a copy.
Example 4 · A getter that leaks a private array
import java.util.Arrays;
class MarksCard { private int[] marks;
public MarksCard(int[] marks) { this.marks = Arrays.copyOf(marks, marks.length); }
public int[] getMarks() { return marks; // hands out the real array }
public int getTotal() { int sum = 0; for (int m : marks) { sum += m; } return sum; }}
public class GetterLeakDemo { public static void main(String[] args) { MarksCard card = new MarksCard(new int[] {45, 60, 52}); System.out.println("Total: " + card.getTotal()); int[] m = card.getMarks(); m[0] = 100; System.out.println("Total: " + card.getTotal()); }}Total: 157 Total: 212
What this code does
getMarks()returns the address of the private array, somand the field point to the same array.m[0] = 100;changes the object’s marks with no setter and no check. The total jumps from 157 to 212.
Example 5 · A constructor that keeps the caller’s array
import java.util.Arrays;
class MarksCard { private int[] marks;
public MarksCard(int[] marks) { this.marks = marks; // keeps the caller's array }
public int[] getMarks() { return Arrays.copyOf(marks, marks.length); }}
public class CtorLeakDemo { public static void main(String[] args) { int[] scores = {45, 60, 52}; MarksCard card = new MarksCard(scores); scores[1] = 0; System.out.println(Arrays.toString(card.getMarks())); }}[45, 0, 52]
What this code does
- The getter copies, but the constructor saved the address of
scores.mainstill holds that address. - Changing
scoreslater changes the card. Copying in only one place is not enough.
The constructor leaks the same way: this.marks = marks; keeps the caller's array, and the caller can still change it later.
private protects the variable, not the array it points to. Once someone has the address, private cannot stop them.Defensive copies close the leak
A defensive copy is a new array with the same values. Copy in two places: in the constructor (what you receive) and in the getter (what you hand out).
Example 6 · Copies in both places: nothing leaks
import java.util.Arrays;
class MarksCard { private int[] marks;
public MarksCard(int[] marks) { this.marks = Arrays.copyOf(marks, marks.length); }
public int[] getMarks() { return Arrays.copyOf(marks, marks.length); }}
public class SafeCopyDemo { public static void main(String[] args) { int[] scores = {45, 60, 52}; MarksCard card = new MarksCard(scores); scores[1] = 0; int[] m = card.getMarks(); m[0] = 100; System.out.println(Arrays.toString(card.getMarks())); }}[45, 60, 52]
What this code does
- The constructor keeps its own copy, so changing
scoresafterwards does not matter. - The getter returns a fresh copy, so
m[0] = 100;changes only that copy. The card is truly read-only.
Arrays.copyOf(marks, marks.length), from The Arrays class (opens in a new tab), makes the copy in one line. An int or String field needs no copy: an int is copied when it is returned, and a String can never be changed.
Next step
Check your understanding
12 quick questions