Common mistakes and practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most bugs in this module come from one question asked wrongly: who decides, the declared type or the object? The rest come from objects meant to be immutable that still have a way in or a way out.
Mistakes and fixes at a glance
The classic crash: casting every element of a parent-type array to one child type. The cast compiles, because a Payment could be a UPI payment, and fails on the first element that is not.
Example 1 · Bug: casting without a check
class Payment { int amount;
Payment(int amount) { this.amount = amount; }}
class UpiPayment extends Payment { UpiPayment(int amount) { super(amount); }
int cashback() { return amount / 100; }}
public class CashbackBug { public static void main(String[] args) { Payment[] list = { new UpiPayment(500), new Payment(300), new UpiPayment(900) }; int total = 0; for (Payment p : list) { UpiPayment u = (UpiPayment) p; total = total + u.cashback(); } System.out.println("Cashback: Rs. " + total); }}Exception in thread "main" java.lang.ClassCastException: class Payment cannot be cast to class UpiPayment (Payment and UpiPayment are in unnamed module of loader 'app') at CashbackBug.main(CashbackBug.java:24)
What this code does
- The cast compiles because a
Paymentcould be aUpiPayment. The second element is a plainPayment, so the JVM throws. - The message names the object type first:
class Payment cannot be cast to class UpiPayment.
Example 2 · Fix: check with a pattern
class Payment { int amount;
Payment(int amount) { this.amount = amount; }}
class UpiPayment extends Payment { UpiPayment(int amount) { super(amount); }
int cashback() { return amount / 100; }}
public class CashbackFix { public static void main(String[] args) { Payment[] list = { new UpiPayment(500), new Payment(300), new UpiPayment(900) }; int total = 0; for (Payment p : list) { if (p instanceof UpiPayment u) { total = total + u.cashback(); } } System.out.println("Cashback: Rs. " + total); }}Cashback: Rs. 14
What this code does
- Only real
UpiPaymentobjects pass the test, anduis already cast. 5 + 9 = 14. - Cashback is an optional extra that only some payments have, so
instanceofis reasonable here. If every type had its own rule, an overriddencashback()would be better.
Review: instanceof and pattern matching (opens in a new tab). The other common mistakes, each with what goes wrong and the fix:
incompatible types: Payment cannot be converted to UpiPaymentonUpiPayment u = p;→ javac sees only declared types; keep a child-type variable, or cast. Review: Reference type vs object type (opens in a new tab)incompatible types: Cat cannot be converted to Dogon(Dog) myCat→ siblings can never be cast to each other. Review: Downcasting (opens in a new tab)cannot find symbolon a pattern variable, orinstanceof Dog d || ...→ the variable exists only where the test is true; use it inside theifor after&&. Review: instanceof and pattern matching (opens in a new tab)p.nameandp.getName()disagree, orstatic methods cannot be annotated with @Override→ fields and static methods follow the declared type; keep fields private and call statics by class name. Review: Field hiding vs method overriding (opens in a new tab)s.trim();ort.withSeat(...)on its own line changes nothing → store the new object:s = s.trim();. Review: Immutable objects (opens in a new tab)- An "immutable" object changes from outside → copy arrays in the constructor and the getter, and make the class
final. Review: Design your own immutable class (opens in a new tab) cannot find symbolons.getName()for a record, orcannot assign a value to final variable→ accessors have noget, and a with-method returns a new record. Review: Records (opens in a new tab)non-static variable ... cannot be referenced from a static context, oran enclosing instance ... is required→ a static nested class has no outer object; an inner one needsouter.new Inner(). Review: Nested classes (opens in a new tab)
Fields and static methods do not follow the object
Only overridden instance methods follow the object. Fields and static methods are picked by the compiler from the declared type, and code written in the parent reads the parent's field.
Example 3 · Trace: hidden field, static method, overridden method
class Phone { String brand = "Generic";
static String type() { return "phone"; }
String describe() { return brand + " " + type() + " " + model(); }
String model() { return "basic"; }}
class Pixel extends Phone { String brand = "Google";
static String type() { return "smartphone"; }
@Override String model() { return "Pixel 8"; }}
public class PhoneTrace { public static void main(String[] args) { Phone p = new Pixel(); System.out.println(p.brand + " | " + p.type() + " | " + p.model()); System.out.println(p.describe()); System.out.println(((Pixel) p).brand + " | " + Pixel.type()); }}Generic | phone | Pixel 8 Generic phone Pixel 8 Google | smartphone
What this code does
p.brandandp.type()follow the reference typePhone;p.model()follows the object. Insidedescribe()(written inPhone),brandandtype()arePhone's too.- Only the cast or the class name reaches
Pixel's field and static method.
When tracing, label every name: field, static method or overridden instance method. Use the declared type (or the class where the code is written) for the first two, and the object for the third.
How "immutable" classes leak
A class can have only private final fields and still change. Three doors stay open in the next program: the caller's array, the getter's array and a child class.
Example 4 · Bug: an "immutable" class with three leaks
import java.util.Arrays;
class Marksheet { private final String name; private final int[] marks;
Marksheet(String name, int[] marks) { this.name = name; this.marks = marks; }
int[] getMarks() { return marks; }
@Override public String toString() { return name + " " + Arrays.toString(marks); }}
class FakeMarksheet extends Marksheet { FakeMarksheet(String name, int[] marks) { super(name, marks); }
@Override public String toString() { return "Topper [100, 100]"; }}
public class LeakReview { public static void main(String[] args) { int[] input = { 60, 70 }; Marksheet m = new Marksheet("Arjun", input); input[0] = 0; m.getMarks()[1] = 0; Marksheet fake = new FakeMarksheet("Arjun", new int[] { 60, 70 }); System.out.println(m); System.out.println(fake); }}Arjun [0, 0] Topper [100, 100]
What this code does
- Leak 1: the caller's array is stored. Leak 2: the getter returns the inside array. Both set marks to 0 from outside.
- Leak 3: the class is not
final, so a child pretends to be a marksheet with other marks. Fix:final class, plusArrays.copyOfin the constructor and the getter.
The fix closes each door: final class, Arrays.copyOf in the constructor and Arrays.copyOf in the getter. For plain values without arrays, a record does all of this in one line.
Spot the bug
Each snippet below looks almost right. Read what it should do, tap the wrong line, then check the fix. Ask two questions: which type does the compiler see, and is a new object being thrown away?
Find the bug
Find the module bug
Select the line that is wrong.
Print the UPI id only when p is a UPI payment.
Round 1 of 5Trace before you guess
When an output surprises you, trace it. For every name ask: field, static method or overridden method? Then use the declared type or the object, and never guess.
Trace the code
Trace fields, methods and a cast
Variables
- p
- StudentPass object
Output
(nothing printed yet)Line 19One StudentPass object holding two price fields: 500 from Pass and its own 250. p is declared as Pass.
Finish up
Mark complete & continue
Next: Must-do problems: References, Casting and Immutability