Unit 1 home
CLASS 12 · PART E UNIT-1 CLOSE · COVARIANTS + MISTAKES UNIT I · UI24PC320CS
CLASS 12 · P 1/13PGDN NEXT POINT · PGUP BACK
K TRISHAANK · OOP THROUGH JAVA · UNIT I · PART E · THE UNIT-1 FINALE

Unit 1 closes by naming what still trips freshers.

Eleven classes ago Java was a rumour. Today you own classes, objects, constructors, static, the memory map, extends, abstract classes and interfaces. One class remains before Eclipse: the three inheritance mistakes interviewers fish for, one last friendly rule (covariant returns) — and a full-unit recap that leaves nothing fuzzy before Lab 2.

THE ARCthree classic mistakes, watched live · covariant returns · two notebook activities · recap, checklist, quiz, cheat-sheet · the bridge to Lab 2
TODAY'S SHAPEa bridge class — NO new heavy machinery, NO PYQ; consolidation and honest self-testing
PART-E SPINEDeliveryPartner rides one last time — and the food app's order queue gets smarter
FEEDSLAB 2 · Eclipse first lab · C14 encapsulation (the silent fourth pillar)
C10 · INHERITANCE C11 · ABSTRACT + INTERFACE C12 · UNIT-1 CLOSE — YOU ARE HERE LAB 2 · ECLIPSE UNIT 2

The hook, before anything else: every campus placement season, the SAME three inheritance slips knock out fresher after fresher — and none of them is exotic. Each one is a program you could type today, that compiles cleanly, and then quietly does the wrong thing. Watching all three break — on purpose, in tiny programs — is the cheapest interview preparation you will ever do.

PART 2 · WHAT TODAY DELIVERS

Three traps. One friendly rule. One honest recap.

WHY THIS CLASS HAS NO PYQ CHIP Class 12 is a bridge class — no new exam question lands here, on purpose. Its job is consolidation: catch the mistakes early, close Unit 1 honestly, and walk you into Lab 2 with a checklist you actually ticked. The pillar teach-back you do today is deliberately three-quarters: Encapsulation is taught formally at Class 14, and the full four-pillar version returns at the Unit-2 close.

BY THE END YOU CAN

  • Debugthe three classic inheritance mistakes — constructor-calls-overridable, field shadowing, unsafe casts — on sight, with the one-line fix for each.
  • Classifywhich return-type changes are legal in an override — the covariant rule — and why the same change is ILLEGAL in an overload.
  • Recapall of Unit 1 out loud: three pillars with your own examples, every keyword's one-line job, and an honest tick-list of what still needs a re-read.

WHERE THIS SITS

TODAY'S ROUTE · 12 STOPS

  • Mistake 1 — a constructor that calls an overridable methodDISCOVERY
  • Mistake 2 — a child field that SHADOWS the parent'sDISCOVERY
  • Mistake 3 — the cast that compiles but explodes at run timeDISCOVERY
  • Covariant return types — the friendly last rule of overridingCORE
  • Worked build — FoodApp.getNextOrder(), typed liveCODE
  • Activity 1 — hunt the shadowed field in TopRatedDeliveryPartnerNOTEBOOK
  • Activity 2 — teach back three pillars, PREDICT the fourthNOTEBOOK
  • Unit-1 recap + exam strategyCORE
  • Self-check checklist — tick what you can truly explainINTERACTIVE
  • Quick quiz — 5 true/false, verdicts revealed one per pressQUIZ
  • Keyword cheat-sheet — 9 keywords, one line eachCORE
  • Reflection + the bridge to Lab 2 and Unit 2CLOSE

CLASS 12 OF 60 · 14 PAGES · 13 PARTS · BRIDGE CLASS — 0 PYQ · UNIT 1 ENDS ON THIS PAGE

PART 3 · MISTAKE 1 OF 3

A constructor that shouts
into an unfinished room.

Story first, no code yet. A new gaming account is being set up. The setup clerk (the parent constructor) finishes his page and shouts "announce the player's rank!" — but the rank sticker (the child's field) hasn't been pasted on yet; the child's page of the form is still blank. Whoever answers the shout can only read what exists right now. That is Mistake 1 in one scene: a constructor calling a method that a child can override — the override runs BEFORE the child's fields exist.

WATCH THE ORDER OF EVENTS — ONE STEP PER PRESS

STEP 1

new RankedAccount("Krish") begins. Java's iron rule from Class 10: the parent's constructor always runs first.

STEP 2

Inside the parent constructor sits an innocent-looking line: showRank();. Dynamic dispatch does its job perfectly — it runs the CHILD's override. Perfectly… and too early.

STEP 3

The child's override reads rankName — but the child constructor hasn't run yet, so rankName still holds Class 9's default for an unassigned reference field: null.

Player rank: null

STEP 4

Only NOW does the child constructor run and write rankName = "Gold IV"; — politely fixing a field the program already printed. Too late; the wrong line is on screen forever.

The shout was on time. The room wasn't ready.

NOW THE SAME SCENE AS A COMPLETE PROGRAM — ONE LINE PER PRESS

MINI PROBLEM · RANKEDACCOUNT.JAVA
PROBLEM
Build the smallest program that shows Mistake 1: a parent constructor calls a method the child overrides — and the child's field is read before it exists.
REQUIRE­MENTS
  • Save as RankedAccount.java in java-practice\class-12\ — two classes, one file
  • GameAccount's constructor calls showRank()
  • RankedAccount overrides showRank() and reads its own field rankName
  • The child constructor sets rankName = "Gold IV" — predict the output BEFORE running
EXPECTED OUTPUT
Not Player rank: Gold IV — the terminal prints Player rank: null, exactly as the sim predicted.
SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\diya\Desktop\java-practice\class-12\RankedAccount.java
RankedAccount.java — THE SHOUT INTO THE UNFINISHED ROOM
1class GameAccount
2{
3 GameAccount()
4 {
5 showRank(); // the shout — runs the CHILD's version
6 }
7 void showRank()
8 {
9 System.out.println("No rank yet");
10 }
11}
12
13class RankedAccount extends GameAccount
14{
15 String rankName; // born null (Class 9's default rule)
16 RankedAccount()
17 {
18 rankName = "Gold IV"; // runs AFTER the parent's shout
19 }
20 void showRank()
21 {
22 System.out.println("Player rank: " + rankName);
23 }
24 public static void main(String[] args)
25 {
26 new RankedAccount();
27 }
28}
COMMAND PROMPT

C:\Users\diya\Desktop\java-practice\class-12> javac RankedAccount.java

C:\Users\diya\Desktop\java-practice\class-12> java RankedAccount

Player rank: null

↳ compiles CLEAN — no error, no warning. The wrongness is purely in the ORDER of events: parent constructor → child's override → child constructor. That is what makes this trap famous.

The fix is a design habit, not a patch: a constructor should only do quiet setup — assign fields, nothing else. Never call a method a child can override from inside a constructor. If the parent truly must call something, make that method final (Class 10's lock) so no child can swap it.
Interview phrasing, worth memorising:

"During construction of a subclass object, the superclass constructor runs first; if it calls an overridden method, the subclass version executes before the subclass constructor has initialised its fields — so those fields still hold their defaults (null, 0, false)." One sentence, full marks, and you have now WATCHED it happen.

PART 4 · MISTAKE 2 OF 3

One object.
TWO boxes with the same name.

Story first. A streaming account upgrades to Premium — ₹149 paid, receipt on screen. But the app keeps greeting them "Plan: Free". Why? The child class didn't change the parent's plan box — it accidentally built a second box with the same name next to it. Both boxes live inside the same object, and different lines of code read different boxes. Class 11 taught you methods override. Fields never do that. Fields only hide — and hiding is Mistake 2.

THE TRAP, ONE MOVE PER PRESS

STEP 1

Account owns String plan = "Free";. Then PremiumAccount extends Account writes String plan = "Premium"; — and Java does NOT replace the parent's box. It quietly adds a second box named plan. One object, two boxes.

STEP 2

Which box does a read pick? Here is the rule that separates toppers from the rest: for FIELDS, the slip (reference type) decides — at compile time. So a.plan through an Account slip reads the parent's box: Free. No dynamic dispatch. Fields never get it.

STEP 3

Worse: p.showPlan() looks safe — a child slip! But showPlan() was written inside Account, so its code was compiled reading Account's box. The paying customer gets:

Plan: Free

STEP 4

The fix costs one word. Never re-declare a field the parent already owns. Delete the type: instead of String plan = "Premium"; the child's constructor simply ASSIGNS the inherited box — plan = "Premium";. One box, one truth, bug gone.

Methods override. Fields hide. Only one of those is polymorphism.

SEE THE TWO BOXES — DRAWN LIVE, ONE PRESS EACH

ONE OBJECT ON THE HEAP · 77 ACCOUNT'S LAYER (inherited) plan = "Free" PREMIUMACCOUNT'S LAYER (re-declared) plan = "Premium" Account a the parent slip a.plan → READS THIS BOX PremiumAccount p the child slip p.plan → READS THIS BOX SAME OBJECT · TWO BOXES · THE SLIP PICKS THE BOX

Both slips point at the SAME object — yet they read different answers. That is why shadowing bugs feel haunted.

NOW THE FULL PROGRAM — ONE LINE PER PRESS · PREDICT ALL THREE OUTPUT LINES FIRST

MINI PROBLEM · PREMIUMACCOUNT.JAVA
PROBLEM
Build the smallest program that shows Mistake 2: a child re-declares a field the parent already owns — then read it three different ways and watch three different answers.
REQUIRE­MENTS
  • Save as PremiumAccount.java in java-practice\class-12\ — two classes, one file
  • BOTH classes declare String plan — parent "Free", child "Premium"
  • Make one object, hold it with a child slip p AND a parent slip a
  • Print a.plan, then p.plan, then call p.showPlan() — write your three predictions in the notebook BEFORE running
EXPECTED OUTPUT
Three lines — and the paying customer is called Free in two of them.
SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\diya\Desktop\java-practice\class-12\PremiumAccount.java
PremiumAccount.java — ONE OBJECT, TWO BOXES
1class Account
2{
3 String plan = "Free"; // box 1
4 void showPlan()
5 {
6 System.out.println("Plan: " + plan); // compiled reading BOX 1
7 }
8}
9
10class PremiumAccount extends Account
11{
12 String plan = "Premium"; // MISTAKE — box 2, same name
13 public static void main(String[] args)
14 {
15 PremiumAccount p = new PremiumAccount();
16 Account a = p; // SAME object, parent slip
17 System.out.println(a.plan); // slip decides → box 1
18 System.out.println(p.plan); // slip decides → box 2
19 p.showPlan(); // method's OWN class → box 1
20 }
21}
COMMAND PROMPT

C:\Users\diya\Desktop\java-practice\class-12> javac PremiumAccount.java

C:\Users\diya\Desktop\java-practice\class-12> java PremiumAccount

Free

Premium

Plan: Free

↳ compiles CLEAN again — the compiler is perfectly happy with two boxes. Line 17 and line 19 both betray the paying customer, each for a different reason: the slip's type, and the method's home class.

The one-word fix, spelled out: in line 12, delete String and move the assignment into a constructor — plan = "Premium";. Now the child WRITES INTO the inherited box instead of building a rival one. All three prints agree. Modern IDEs even warn you: "field hides field in supertype" — Eclipse will show you that warning in Lab 2.
Interview phrasing, worth memorising:

"Fields are resolved by the compile-time type of the reference (static binding); methods are resolved by the runtime type of the object (dynamic dispatch). A re-declared field therefore hides the parent's field — it never overrides it." Hold this scene tight: Activity 1 at stop 8 hands you a delivery-app bug built from exactly this trap, and you will fix it yourself.

PART 5 · MISTAKE 3 OF 3

The cast that promises
what the object never was.

Last mistake, and the only one of the three that crashes. Story: the college fest gate. Everyone in the queue holds a generic Ticket slip. A volunteer grabs one and announces "this is a VIP pass!" — writes (VIPTicket) in front of it — without checking. If the person really bought VIP, fine. If they bought a normal ticket, the announcement doesn't make them VIP — the gate machine rejects it on the spot. In Java that rejection has a famous name: ClassCastException. And unlike Mistakes 1 and 2, this one stops the whole program.

TWO CASTS, TWO FATES — ONE STEP PER PRESS

STEP 1

From Class 11 you already know the safe direction: upcast. Ticket t = new VIPTicket(); — child object, parent slip. Always legal, no bracket needed, nothing can go wrong. The queue accepts every specific ticket as "a ticket".

STEP 2

The reverse — downcast — needs the bracket: VIPTicket v = (VIPTicket) t;. The bracket is YOU signing a promise: "compiler, trust me, the object at the end of this slip really is a VIPTicket." The compiler stops checking. The RUNTIME doesn't.

STEP 3

Break the promise — the object was new Ticket() all along — and the JVM checks the heap tag at the moment of the cast, finds a plain Ticket, and throws:

Exception in thread "main" java.lang.ClassCastException: class Ticket cannot be cast to class VIPTicket

STEP 4

The fix is the guard you met in Class 11: ask before you announce. if (t instanceof VIPTicket) — only then cast. instanceof reads the object's real heap tag, so the guarded cast can never blow up.

A cast never changes the object. It only changes the promise — and broken promises crash at runtime.

NOW WATCH IT CRASH FOR REAL — ONE LINE PER PRESS

MINI PROBLEM · FESTGATE.JAVA
PROBLEM
Build the smallest program that shows Mistake 3 twice: one honest downcast that works, one dishonest downcast that throws ClassCastException — then guard it with instanceof.
REQUIRE­MENTS
  • Save as FestGate.java in java-practice\class-12\ — two classes, one file
  • Ticket parent; VIPTicket extends Ticket with its own method loungeAccess()
  • Downcast a slip that REALLY holds a VIPTicket — watch it work
  • Downcast a slip that holds a plain Ticket — predict the exact exception line, then run
EXPECTED OUTPUT
One happy lounge line, then a red ClassCastException — and note which printed lines never got the chance to run.
SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\diya\Desktop\java-practice\class-12\FestGate.java
FestGate.java — THE HONEST AND THE DISHONEST CAST
1class Ticket
2{
3 void scan()
4 {
5 System.out.println("Ticket scanned");
6 }
7}
8
9class VIPTicket extends Ticket
10{
11 void loungeAccess()
12 {
13 System.out.println("Lounge open. Welcome!");
14 }
15 public static void main(String[] args)
16 {
17 Ticket honest = new VIPTicket(); // really VIP under the slip
18 ((VIPTicket) honest).loungeAccess(); // promise kept — works
19
20 Ticket plain = new Ticket(); // just a Ticket. nothing more
21 ((VIPTicket) plain).loungeAccess(); // promise BROKEN — crashes HERE
22
23 System.out.println("Gate closing"); // never reached
24 }
25}
COMMAND PROMPT

C:\Users\diya\Desktop\java-practice\class-12> javac FestGate.java

C:\Users\diya\Desktop\java-practice\class-12> java VIPTicket

Lounge open. Welcome!

Exception in thread "main" java.lang.ClassCastException: class Ticket cannot be cast to class VIPTicket

at VIPTicket.main(FestGate.java:21)

↳ read the exception like a sentence: WHAT went wrong (Ticket cannot be cast to VIPTicket), and WHERE (line 21). "Gate closing" never printed — a ClassCastException abandons everything after it.

The guarded version — the only downcast a professional writes:

if (plain instanceof VIPTicket)
{
    ((VIPTicket) plain).loungeAccess();
}

The instanceof check reads the object's REAL heap tag, so a guarded cast can never throw. This exact pairing — check, then cast — earned full marks in the Class 11 PYQ, and it will again.

ALL THREE MISTAKES ON ONE SHELF — YOUR REVISION CARD

MISTAKE 1 · constructor calls an overridable method

Child's override runs before the child's fields exist — prints defaults (null / 0 / false).

SILENT WRONG OUTPUT
MISTAKE 2 · child re-declares a parent field

Two boxes, one name. The slip's compile-time type picks the box — no dynamic dispatch for fields.

SILENT WRONG OUTPUT
MISTAKE 3 · downcast without instanceof

The bracket is a promise the compiler stops checking. Break it → the runtime throws, the program dies.

CLASSCASTEXCEPTION · CRASH

Two mistakes lie to you quietly. One shouts. The quiet ones are the dangerous ones.

PART 6 · THE NEW IDEA — COVARIANT RETURNS

An override may promise
something more specific.

Mistakes done — now today's one genuinely NEW rule, and it is a friendly one. Class 11 told you an override must keep the same signature. Almost true. Java relaxes exactly ONE part: the return type. An override is allowed to return a subclass of what the parent promised. That relaxation has a fancy exam name: covariant return types.

THE IDEA IN ONE EVERYDAY SCENE — ONE STEP PER PRESS

STEP 1

A canteen menu promises: "ordering dessert returns a Dessert." The premium counter's menu says: "ordering dessert here returns a Cheesecake." Did the premium counter break the promise?

STEP 2

No — it strengthened it. Every Cheesecake IS a Dessert (the is-a test from Class 10). Anyone who believed the parent's promise still gets exactly what they were promised, plus more precision. That is why Java allows it.

STEP 3

The reverse is forbidden. If the parent promises a Cheesecake and the child tries to return any old Dessert, believers of the promise could receive a fruit bowl. The compiler rejects it on the spot — widening the return type is a compile error.

Narrower return: allowed. Wider return: refused. The promise may only get stronger.

THE SMALLEST POSSIBLE COVARIANT OVERRIDE — ONE LINE PER PRESS

MINI PROBLEM · CANTEEN.JAVA
PROBLEM
Write the tiniest legal covariant override: parent method returns Dessert, child override returns Cheesecake — and prove through a parent slip that the caller still works untouched.
REQUIRE­MENTS
  • Save as Canteen.java in java-practice\class-12\
  • Dessert parent, Cheesecake extends Dessert — each with a name()-style print
  • Counter.serve() returns Dessert; PremiumCounter.serve() overrides it returning Cheesecake
  • Call serve() through a Counter slip — the caller's code must not change at all
EXPECTED OUTPUT
The premium counter's cheesecake line — reached through plain parent-typed code.
SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\diya\Desktop\java-practice\class-12\Canteen.java
Canteen.java — THE PROMISE THAT GOT STRONGER
1class Dessert
2{
3 void describe()
4 {
5 System.out.println("Some dessert");
6 }
7}
8
9class Cheesecake extends Dessert
10{
11 void describe()
12 {
13 System.out.println("Blueberry cheesecake!");
14 }
15}
16
17class Counter
18{
19 Dessert serve() // promises: a Dessert
20 {
21 return new Dessert();
22 }
23}
24
25class PremiumCounter extends Counter
26{
27 Cheesecake serve() // COVARIANT — narrower, legal
28 {
29 return new Cheesecake();
30 }
31 public static void main(String[] args)
32 {
33 Counter c = new PremiumCounter(); // parent slip, as always
34 c.serve().describe(); // caller unchanged
35 }
36}
COMMAND PROMPT

C:\Users\diya\Desktop\java-practice\class-12> javac Canteen.java

C:\Users\diya\Desktop\java-practice\class-12> java PremiumCounter

Blueberry cheesecake!

↳ two dispatches in one line 34: c.serve() dynamically runs the PREMIUM counter's override (returning a Cheesecake), then .describe() dynamically runs the CHEESECAKE's override. Everything from Class 11, plus one narrower return type.

Why anyone bothers: callers who KNOW they hold a PremiumCounter slip get a Cheesecake back directly — Cheesecake ck = pc.serve(); — with no downcast and no instanceof. Covariant returns exist precisely to delete Mistake-3-style casts from your code. One rule, one mistake prevented.
Exact exam definition — write it like this:

"A covariant return type means an overriding method may declare a return type that is a subclass of the return type declared in the superclass method. All other parts of the signature — name and parameter list — must still match exactly." Since Java 5. The parameter list gets NO such freedom: change it and you are overloading, not overriding (the Class 11 trap).

PART 7 · WORKED BUILD — COVARIANCE EARNING ITS SALARY

FoodApp: the override that
deleted a downcast.

Cheesecake proved the rule. Now watch it earn money in an app you actually use. A food-delivery backend has a plain FoodApp whose getNextOrder() hands the kitchen the next Order. The premium tier, PrimeFoodApp, always serves a PriorityOrder — which carries an extra promise: etaMinutes(). Old code before covariance had to CAST to reach it. We will build both versions and watch the cast disappear.

DESIGN FIRST — THE FOUR CLASSES AND THEIR EDGES, ONE PRESS EACH

Order describe() — what the kitchen reads PriorityOrder + etaMinutes() — the extra promise extends FoodApp Order getNextOrder() — promises an Order PrimeFoodApp PriorityOrder getNextOrder() — COVARIANT extends returns an Order returns a PriorityOrder BOTH TOWERS NARROW TOGETHER — THAT IS COVARIANCE IN ARCHITECTURE

Left tower narrows (FoodApp → PrimeFoodApp). Right tower narrows (Order → PriorityOrder). The return edge is allowed to narrow WITH them.

THE FULL BUILD — ONE LINE PER PRESS · WATCH LINE 27 KILL THE CAST

MINI PROBLEM · FOODAPP.JAVA
PROBLEM
Implement the diagram: PrimeFoodApp.getNextOrder() overrides covariantly, returning PriorityOrder instead of Order — then call etaMinutes() with zero casts and zero instanceof.
REQUIRE­MENTS
  • Save as FoodApp.java in java-practice\class-12\ — four classes, one file
  • Order.describe() prints the dish; PriorityOrder extends Order adds etaMinutes()
  • FoodApp.getNextOrder() returns Order; the Prime override returns PriorityOrder
  • In main, prove BOTH views work: a parent slip that only needs describe(), and a prime slip that reaches etaMinutes() cast-free
EXPECTED OUTPUT
The dish line twice (once per view) and the ETA line — no (PriorityOrder) bracket anywhere in the file.
SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\diya\Desktop\java-practice\class-12\FoodApp.java
FoodApp.java — COVARIANCE DELETES THE DOWNCAST
1class Order
2{
3 void describe()
4 {
5 System.out.println("Order: Paneer Biryani");
6 }
7}
8
9class PriorityOrder extends Order
10{
11 void etaMinutes()
12 {
13 System.out.println("Priority ETA: 18 minutes");
14 }
15}
16
17class FoodApp
18{
19 Order getNextOrder()
20 {
21 return new Order();
22 }
23}
24
25class PrimeFoodApp extends FoodApp
26{
27 PriorityOrder getNextOrder() // covariant — the whole point
28 {
29 return new PriorityOrder();
30 }
31 public static void main(String[] args)
32 {
33 FoodApp kitchenView = new PrimeFoodApp();
34 kitchenView.getNextOrder().describe(); // old code, untouched
35
36 PrimeFoodApp primeView = new PrimeFoodApp();
37 PriorityOrder po = primeView.getNextOrder(); // NO cast!
38 po.describe();
39 po.etaMinutes();
40 }
41}
COMMAND PROMPT

C:\Users\diya\Desktop\java-practice\class-12> javac FoodApp.java

C:\Users\diya\Desktop\java-practice\class-12> java PrimeFoodApp

Order: Paneer Biryani

Order: Paneer Biryani

Priority ETA: 18 minutes

↳ line 37 is the money line. Before Java 5 it HAD to be written PriorityOrder po = (PriorityOrder) primeView.getNextOrder(); — a Mistake-3 bracket waiting to break. Covariance made the compiler prove it instead.

Connect the dots backwards: Part 5 warned you the downcast bracket is a runtime gamble. Part 6 gave you the rule that removes it. Part 7 just showed the rule at work in production-shaped code. When an interviewer asks "why do covariant return types exist?", the winning answer is one line: "so callers with a specific slip get a specific object back without an unsafe cast."

PART 8 · ACTIVITY 1 — DEBUGGING · NOTEBOOKS OUT, EYES SHARP

The five-star partner the app
keeps calling a rookie.

THE SCENE A delivery-app teammate ships this. Every TopRatedDeliveryPartner is created with rating 4.9 — yet the badge printer greets them all with Rating: 0.0. The teammate swears "the field IS set, I can see the line!" You now know a mistake that behaves exactly like this.

class DeliveryPartner
{
double rating;
void printBadge()
{
System.out.println("Rating: " + rating);
}
}
class TopRatedDeliveryPartner extends DeliveryPartner
{
double rating = 4.9; // "the field IS set, I can see the line!"
public static void main(String[] args)
{
TopRatedDeliveryPartner t = new TopRatedDeliveryPartner();
t.printBadge(); // prints Rating: 0.0 … why?!
}
}

YOUR TASK In the notebook, each answer on its own line:

  • Name the mistake (its Part-4 name) and point to the guilty line.
  • Explain in one sentence WHY printBadge() reads 0.0 even though 4.9 is clearly assigned. Mention which class printBadge() lives in.
  • How many rating boxes does the object t carry on the heap? Draw them.
  • Fix it so the badge prints Rating: 4.9 — WITHOUT touching DeliveryPartner, and without adding any new method.

All four in the notebook first — especially the drawing. The drawing IS the understanding.

SOLUTION SHEET · ACTIVITY 1 — THE HAUNTED RATING
  • Q1Field shadowing (Mistake 2). Guilty line: double rating = 4.9; inside the child — it re-declares a field the parent already owns.
  • Q2printBadge() lives in DeliveryPartner, so its code was compiled reading DeliveryPartner's rating box — which nobody ever assigned, so it holds the default 0.0. Fields never dispatch dynamically.
  • Q3Two boxes. One object on the heap carrying DeliveryPartner.rating = 0.0 in its parent layer and TopRatedDeliveryPartner.rating = 4.9 in its child layer — the Part-4 diagram, redrawn with your pen.
  • Q4Delete the re-declaration; assign the INHERITED box instead, from a child constructor:
class TopRatedDeliveryPartner extends DeliveryPartner
{
TopRatedDeliveryPartner()
{
rating = 4.9; // ASSIGN the inherited box — no new declaration
}
// main unchanged — now prints Rating: 4.9
}
  • CHECKNote what the fix did NOT need: no super, no this, no override, no cast. Removing a shadow means removing a declaration — one box, one truth.
  • ECLIPSEIn Lab 2 you will see Eclipse underline the original line with "The field TopRatedDeliveryPartner.rating is hiding a field from type DeliveryPartner" — the IDE catches Mistake 2 before your users do.
  • PROVE ITWords are cheap — type the WHOLE fixed file and run it. Save as BadgeBug.java in class-12\:
// BadgeBug.java — the FIXED file, complete and runnable
class DeliveryPartner
{
double rating;
void printBadge()
{
System.out.println("Rating: " + rating);
}
}
class TopRatedDeliveryPartner extends DeliveryPartner
{
TopRatedDeliveryPartner()
{
rating = 4.9; // ASSIGN the inherited box — the shadow line is GONE
}
public static void main(String[] args)
{
TopRatedDeliveryPartner t = new TopRatedDeliveryPartner();
t.printBadge();
}
}

:: BEFORE the fix (the shadow line still in) — compiles fine, lies at runtime ::

C:\Users\diya\Desktop\java-practice\class-12> javac BadgeBug.java

C:\Users\diya\Desktop\java-practice\class-12> java TopRatedDeliveryPartner

Rating: 0.0

:: AFTER the fix (declaration deleted, constructor assigns) ::

C:\Users\diya\Desktop\java-practice\class-12> javac BadgeBug.java

C:\Users\diya\Desktop\java-practice\class-12> java TopRatedDeliveryPartner

Rating: 4.9

  • WHY 0.0 BEFOREThe broken run is the whole lesson in two lines of terminal: javac said nothing — shadowing is LEGAL — and the badge read the parent's never-assigned box. The compiler is not your safety net here; your eyes are.

PART 9 · ACTIVITY 2 — TEACH-BACK · PAIRS · CLOSE THE LAPTOPS

Three pillars you own.
One you must predict.

THE SCENE Unit 1 secretly handed you three of the four famous pillars of object-oriented programming. Nobody announced them as pillars at the time — that was deliberate. Turn to your partner and teach them back, one minute per pillar, using ONLY examples from our own classes.

YOUR TASK For each, your teach-back must name the pillar, give our example, and end with one sentence of "why it matters":

  • Pillar you met in Class 6–7: bundling state and behaviour into one unit — what did Book keep together, and what word names that pillar?
  • Pillar you met in Class 10: SavingsAccount extends BankAccount — what is reused, and what word names it?
  • Pillar you met in Class 11: one notifyUser() call, three different messages — what decides at runtime, and what word names it?
  • PREDICT the fourth. It is the only pillar we have NOT finished honestly. Hint: think of Book's id field — right now ANY line of code anywhere can write b.id = -999; and no one stops it. What should a class be able to do about that? Give the missing pillar a name — any reasonable name earns the point.

Teach all three OUT LOUD first, then commit to a written prediction. Predictions in ink!

SOLUTION SHEET · ACTIVITY 2 — THE FOUR PILLARS, THREE EARNED + ONE PROMISED
  • PILLAR 1Abstraction (with encapsulation's opening act). Book bundled its fields and its methods into one unit and exposed a simple face — callers say b.describe() without knowing the insides. Why it matters: users of a class need its MENU, not its kitchen.
  • PILLAR 2Inheritance. SavingsAccount extends BankAccount reused every field and method of the parent, adding only what was new. Why it matters: shared behaviour written once, fixed once.
  • PILLAR 3Polymorphism. One notifyUser() call site, three behaviours — the RUNTIME type of the object decides (dynamic dispatch). Why it matters: old calling code keeps working as new subclasses arrive.
  • PILLAR 4Encapsulation — the full, honest version. Full credit for ANY of: "a class should hide its state", "protect its invariants", or "stop arbitrary mutation from outside". The tools that make it real — private, getters and setters that VALIDATE — arrive in Class 14. Today b.id = -999; compiles; after Class 14 it won't even be possible.
  • HONEST NOTEMany books claim you already "did" encapsulation the day you wrote a class. We refuse the shortcut: until a class can DEFEND its fields, the pillar is a promise, not a fact. You predicted a real gap — that is engineer thinking.
  • PROVE THE GAPThe gap is not philosophy — it compiles. Type and run this complete file, LeakyBook.java, and watch a "stranger" line of main corrupt a Book with no one stopping it:
// LeakyBook.java — proof that pillar 4 is still MISSING (runs today, banned after Class 14)
class Book
{
int id;
String title;
Book(int bookId, String bookTitle)
{
id = bookId;
title = bookTitle;
}
void describe()
{
System.out.println("Book #" + id + ": " + title);
}
}
class LeakyBook
{
public static void main(String[] args)
{
Book b = new Book(42, "Clean Code");
b.describe();
b.id = -999; // a stranger rewrites the id — NOBODY stops this line
b.describe();
}
}

C:\Users\diya\Desktop\java-practice\class-12> javac LeakyBook.java

C:\Users\diya\Desktop\java-practice\class-12> java LeakyBook

Book #42: Clean Code

Book #-999: Clean Code

  • THE POINTBoth lines printed — no error, no warning, no defence. A negative book id now lives in your "working" program. THAT is the missing pillar, demonstrated: after Class 14, id becomes private and the hot line refuses to compile. Keep this file; you will re-run it then and watch the compiler finally say no.

PART 10 · UNIT-1 RECAP — TWELVE CLASSES IN ONE SWEEP

The whole unit,
told as one story.

Look how far this actually travelled. Say it back as a single arc, because that is how the exam wants you to hold it:

THE ARC — ONE CHAPTER PER PRESS

C1–C5

The machine. Java's promise (write once, run anywhere), the JVM, javac/java, variables, types, control flow — the raw material every later idea stands on.

C6–C8

The object. A class is a blueprint; new builds on the heap; slips (references) point; constructors set the newborn's fields; static belongs to the class itself, not to any object.

C9

The memory. Stack vs heap, default values (null/0/false), unreachable objects, and the garbage collector that made free() unnecessary — you watched 52 live and die.

C10

The family. extends, is-a, constructor chains (parent first — today's Mistake 1 lives here), final as the lock.

C11

The magic. Overriding, dynamic dispatch, upcasts and guarded downcasts (instanceof — today's Mistake 3 lives here), abstract classes that refuse new.

C12

The polish. Today: the three classic traps that separate readers from engineers, plus covariant returns — the rule that deletes casts. Unit 1 is CLOSED.

EXAM STRATEGY — HOW UNIT-1 MARKS ARE ACTUALLY WON

"Predict the output" questions

Nearly always a dispatch-vs-slip trap. Ask two questions in order: WHAT is the object (heap tag)? WHAT is the slip (declared type)? Methods follow the object; fields and method-visibility follow the slip.

2 QUESTIONS, IN ORDER
"Find the error" questions

Check the big five: new on an abstract class · override of a final method · unguarded downcast · changed parameter list pretending to override · child re-declaring a parent field.

THE BIG-FIVE SCAN
"Define / differentiate" questions

Every definition you memorised this unit is TWO-sided: overriding vs overloading, upcast vs downcast, hide vs override, abstract vs concrete. Always answer with BOTH sides and one micro-example.

BOTH SIDES + EXAMPLE
Code-writing questions

Marks hide in the small print: Allman braces, the semicolon on an abstract method heading, extends spelled before the parent, a main that actually demonstrates the behaviour asked for.

SMALL PRINT = MARKS

Twelve classes → four question shapes. Own the shapes and the unit owns itself.

PART 11 · SELF-CHECK — TICK ONLY WHAT YOU CAN EXPLAIN OUT LOUD

Before Lab 2:
the honesty checklist.

One line per syllabus item. The rule: tick a box ONLY if you could explain that line to your partner without opening any notes. Unticked boxes are not failures — they are your personal revision list, and they are gold.

  • C1–C3
  • C6–C7
  • C8·C10
  • C8
  • C9
  • C10
  • C11
  • C11·C12
  • C11·C12
  • C10–C11
  • C12
  • C12

QUICK QUIZ — FIVE TRUE/FALSE, WHOLE-UNIT SPAN

Commit before you peek.
Verdicts land per press.

Write T or F for all five in the notebook FIRST. Then each press reveals one verdict. (Answers on the same page — the Quick-Quiz format's short-solution allowance.)

1 · "A final method can still be overloaded."

final forbids OVERRIDING (same signature in a child). Overloading is a different signature — a different method entirely. The lock never applied to it.

TRUE
2 · "An abstract class can have a constructor."

It cannot be new-ed directly, but its constructor RUNS every time a child is built — parent-first, Class 10's chain. Abstract ≠ constructor-less.

TRUE
3 · "A child re-declaring a parent's field overrides it."

Fields never override — they HIDE. Two boxes, one name; the slip's compile-time type picks the box. Mistake 2, watched live today.

FALSE
4 · "An override may return a subclass of the parent's declared return type."

That is exactly a covariant return type — legal since Java 5, and the reason line 37 of FoodApp needed no cast.

TRUE
5 · "A downcast that compiles is guaranteed safe at runtime."

The bracket SILENCES the compiler; it convinces the runtime of nothing. If the heap tag disagrees, ClassCastException — Mistake 3's crash.

FALSE

5/5 means Lab 2 will feel easy. 3/5 means tonight's revision list just wrote itself.

PART 12 · THE KEYWORD CHEAT-SHEET — PHOTOGRAPH THIS ONE

Nine keywords.
One line each. The whole unit.

Every keyword Unit 1 taught you, with the one line that survives exam pressure. Copy this table into the last page of your notebook — it is your pre-exam sixty-second warm-up.

KEYWORDTHE ONE LINE THAT MATTERSWHERE IT LIVES
classDeclares a blueprint — state (fields) + behaviour (methods) bundled as one unit.C6
newBuilds one object from the blueprint on the heap and hands back a slip (reference) to it.C7
thisThe current object's own slip — used only when a parameter name shadows a field, never as decoration.C8
superThe parent's view: super(...) picks the parent constructor (line 1 only); super.m() reaches a method the child overrode.C10–C11
staticBelongs to the CLASS, not to any object — one shared copy, reachable without new.C8
finalThe lock: a final variable can't be reassigned, a final method can't be overridden, a final class can't be extended.C10
abstractThe refusal: an abstract class refuses new; an abstract method is a heading ending in ; that children MUST implement.C11
extendsDeclares is-a: the child inherits every non-private field and method — constructors are NOT inherited, they chain.C10
implementsSigns a contract with an interface — met in passing this unit; its full story opens in Unit 2's world.→ AHEAD

Nine words. Twelve classes. If each line above reads as an old friend, Unit 1 is genuinely yours.

PART 13 · REFLECTION — TWO SENTENCES, INK ONLY

The hardest thing you beat
this unit — name it.

REFLECTION Last notebook entry of Unit 1. Exactly two sentences:

  • Sentence 1: which Unit-1 concept felt HARDEST when you first met it? (References vs objects? Constructor chains? Dynamic dispatch? Abstract's refusal? Today's shadowing?) Name it honestly.
  • Sentence 2: what finally made it click — a diagram, a crash, an activity, a partner's explanation? Name the exact moment.

Keep this page. In Unit 3, when generics feel impossible, you will reread it and remember: the hardest thing you ever met is now something you tick off on a checklist.

YOUR PRACTICE FOLDER — THE LAST NOTEPAD-ERA ENTRIES
Desktop\java-practice\
class-11\ — ZeroSalary, Spine11, contracts … (last class)
class-12\
RankedAccount.java — Mistake 1: the shout into the unfinished room
PremiumAccount.java — Mistake 2: one object, two boxes
FestGate.java — Mistake 3: the promise that crashed
Canteen.java — covariance, smallest legal form
FoodApp.java — covariance deleting a downcast
BadgeBug.java — Activity 1: shadow removed, badge honest (0.0 → 4.9)
LeakyBook.java — Activity 2: the missing pillar, proved with -999

Every file so far: Notepad + two commands. That era ends TODAY — next session, an IDE does the typing chores for you.