Skip to content

Lab: premium plans with this and super

☕ Java 17 · Building Child Classes with this and super · 3/3

Goal: build a premium subscription, hit the classic shadowing bug, fix it with this, then use super to read the base price.

Setup: in an empty folder, create Subscription.java, PremiumSub.java and StreamingPlatform.java.

Step 1 — The base plan

public class Subscription {
    protected int price = 10;
}

protected: the child will be able to read it.

Step 2 — The premium plan, with a bug

public class PremiumSub extends Subscription {
    protected int price = 18;
    private int screens;

    PremiumSub(int screens) { screens = screens; }

    void printPlan() {
        System.out.println("Premium plan with " + this.screens + " screens");
    }
}

A PremiumSub now holds two price fields: the parent's 10 and its own 18.

Step 3 — Run it

public class StreamingPlatform {
    public static void main(String[] args) {
        PremiumSub familyPlan = new PremiumSub(4);
        familyPlan.printPlan();
    }
}
$ javac *.java
$ java StreamingPlatform
Premium plan with 0 screens

Zero screens: the parameter screens hides the field, so screens = screens assigns the parameter to itself. The field keeps its default, 0.

Step 4 — Fix it with this

    PremiumSub(int screens) { this.screens = screens; }
Premium plan with 4 screens

Step 5 — Read the base price with super

Add to PremiumSub:

    int upgradeCost() { return price - super.price; }

And two lines at the end of printPlan():

        System.out.println("Premium price: $" + this.price);
        System.out.println("Base price: $" + super.price);

In main, after printPlan():

        System.out.println("Upgrade cost: $" + familyPlan.upgradeCost());
Premium plan with 4 screens
Premium price: $18
Base price: $10
Upgrade cost: $8

price alone means the child's 18; super.price reaches the parent's 10.

Final code

public class PremiumSub extends Subscription {
    protected int price = 18;
    private int screens;

    PremiumSub(int screens) { this.screens = screens; }

    void printPlan() {
        System.out.println("Premium plan with " + this.screens + " screens");
        System.out.println("Premium price: $" + this.price);
        System.out.println("Base price: $" + super.price);
    }

    int upgradeCost() { return price - super.price; }
}

Full code on GitHub

← this and super · Back to the series


🎓 Preparing the OCP Java 17 exam? Exam traps and practice questions for this section → (optional)