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¶
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();
}
}
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¶
Step 5 — Read the base price with super¶
Add to PremiumSub:
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():
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; }
}
← this and super · Back to the series
🎓 Preparing the OCP Java 17 exam? Exam traps and practice questions for this section → (optional)