Skip to lesson

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

CashbackBug.javaJava
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);    }}
Sample output
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 Payment could be a UpiPayment. The second element is a plain Payment, 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

CashbackFix.javaJava
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);    }}
Output
Cashback: Rs. 14

What this code does

  • Only real UpiPayment objects pass the test, and u is already cast. 5 + 9 = 14.
  • Cashback is an optional extra that only some payments have, so instanceof is reasonable here. If every type had its own rule, an overridden cashback() 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:

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

PhoneTrace.javaJava
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());    }}
Output
Generic | phone | Pixel 8
Generic phone Pixel 8
Google | smartphone

What this code does

  • p.brand and p.type() follow the reference type Phone; p.model() follows the object. Inside describe() (written in Phone), brand and type() are Phone'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

LeakReview.javaJava
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);    }}
Output
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, plus Arrays.copyOf in 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 5

Trace 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

class Pass {
int price = 500;
int getPrice() {
return price;
}
String bill() {
return "Rs. " + price + " / Rs. " + getPrice();
}
}
class StudentPass extends Pass {
int price = 250;
@Override
int getPrice() {
return price;
}
}
public class PassTrace {
public static void main(String[] args) {
Pass p = new StudentPass();
System.out.println(p.price);
System.out.println(p.bill());
StudentPass s = (StudentPass) p;
System.out.println(s.price + " " + (s == p));
}
}

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.

Step 1 of 8

Finish up

Mark complete & continue

Next: Must-do problems: References, Casting and Immutability