Unit 1 home
CLASS 11 · PART E CLASSES THAT REFUSE TO BE OBJECTS UNIT I · UI24PC320CS
CLASS 11 · P 1/16PGDN NEXT POINT · PGUP BACK
K TRISHAANK · OOP THROUGH JAVA · UNIT I · PART E BEGINS · MAGENTA

Some classes are born to be extended — never to be built.

Class 10 gave every class a family. Today a strange thing happens: we meet a base class that refuses to be built directly — and Java gives us a keyword to make that refusal official. Then we go one step further: a class that is nothing but promises. Small examples first, always; the big files only after the idea already feels easy.

THE ARCa ₹0-salary bug names abstract · abstract methods · one worked build · interfaces as pure contracts · one class, many contracts
TODAY'S SHAPE4 notebook activities · 2 self-study cards · every new keyword arrives ONLY when a file breaks without it
PART-E SPINEabstract DeliveryPartner + the Payable contract — one story, every page
FEEDSC12 covariants + Unit-1 close · C15 abstract deepened · C16 interface deepened · LAB 2 Eclipse
C9 · MEMORY MAP C10 · INHERITANCE C11 · ABSTRACT + INTERFACE — YOU ARE HERE C12 · UNIT-1 CLOSE LAB 2 · ECLIPSE

The hook, before anything else: in Class 10, new DeliveryPartner() was perfectly normal. Today the food app's designers say something surprising — "a plain 'delivery partner' should never exist on its own; only bike partners, cycle partners, walkers…". Java can enforce that sentence with one keyword. Finding the bug that makes the keyword necessary is our first stop.

PART 2 · WHAT TODAY DELIVERS

Two refusals. Four notebook drills. One contract.

v7.14 RE-HOME · WHY THE "KEY PRINCIPLES OF OOP" PYQ IS NOT ON THIS PAGE PYQ P1·Q11a ("Explain the key principles of OOP", 4m) used to sit in this class. The audit MOVED it to Class 14: a full-marks answer needs Encapsulation, which is not formally taught until then. Today stays honestly focused on one clean fight — abstract vs interface.

BY THE END YOU CAN

  • Designan abstract class with one abstract method for a real product — and defend why it must stay abstract.
  • Classifysix real design scenarios into abstract class or interface — the decision interviewers actually test.
  • Debugthe two compile errors this topic produces first: new on an abstract class, and an interface method with a body.
  • Explainthe interface-vs-abstract table from memory — row by row, with a reason per row, not a chant.

WHERE THIS SITS

TODAY'S ROUTE · 14 STOPS

  • A ₹0-salary bug — the class that should never have been builtDISCOVERY
  • abstract class — micro examples first, then the refusalCODE
  • Abstract METHOD — a heading with no body, overriding made compulsoryCODE
  • Abstract class vs plain superclass — when to reach for whichSELF-STUDY
  • Worked build — the Part-E spine, typed liveCODE
  • Activity 1 — design your own abstract SubscriptionPlanNOTEBOOK
  • Activity 2 — why does new SubscriptionPlan() refuse?NOTEBOOK
  • Interface — a class that is NOTHING but promisesDISCOVERY
  • Interface vs abstract class — THE tableCORE
  • Java-8 default/static methods — a 3-line preview, core at C16SELF-STUDY
  • One class, MANY contracts — the hat sim + a legal commaSIM
  • Payday — one queue pays three different familiesCODE
  • Activity 3 — the interface method that brought a bodyNOTEBOOK
  • Activity 4 — six scenarios, six verdicts + recapNOTEBOOK

CLASS 11 OF 60 · 18 PAGES · 16 CORE + 2 SELF-STUDY · SELF-STUDY CARDS ARE MARKED WHERE THEY LAND

PART 3 · A CLASS THAT SHOULD NEVER BE BUILT

Some words name real things. Some name only ideas.

Before any Java — a two-word warm-up. You can watch a reel — one specific 30-second clip that actually exists. You cannot watch "content" — not any particular clip, just… content. "Content" is a real and useful idea, but nothing on your feed is only content. Watch what happens when Java lets us build the idea anyway.

MICRO PAIR · SAME THREE LINES, OPPOSITE MEANING — WHICH new IS HONEST?

MICRO 1 · Reel — a REAL thing
class Reel
{
int seconds = 30;
}
Reel r = new Reel();
Honest. A reel can actually play on your screen. Building one with new matches reality.
MICRO 2 · Content — only an IDEA
class Content
{
int views;
}
Content c = new Content();
Legal — but a lie. Which content is c? No clip, no audio, no creator. Java compiled a thing that cannot exist.

Java said YES to both. Reality says yes to only one. That gap is today's first bug.

Now the same gap inside the food app: the designers ruled that a "plain" delivery partner must never exist — only bike partners, cycle partners, walkers. A new intern didn't get the memo, typed new DeliveryPartner(), and payroll ran. Predict the payout line before the terminal shows it.

SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\diya\Desktop\java-practice\class-11\ZeroSalary.java
ZeroSalary.java — LEGAL, COMPILES, AND COMPLETELY WRONG
1class DeliveryPartner
2{
3 String name = "unassigned";
4 double baseRate = 0.0; // a plain partner has no vehicle, so no rate
5
6 double calculatePayout()
7 {
8 return baseRate;
9 }
10}
11
12public class ZeroSalary
13{
14 public static void main(String[] args)
15 {
16 DeliveryPartner ghost = new DeliveryPartner(); // the intern's line
17 System.out.println("Weekly payout: Rs. " + ghost.calculatePayout());
18 }
19}
TERMINAL — THE BUG IS QUIET, NOT LOUD
C:\...\class-11> javac ZeroSalary.java
(no errors — the compiler is perfectly happy)
C:\...\class-11> java ZeroSalary
Weekly payout: Rs. 0.0
A partner who exists on payroll and earns ₹0.0 — no crash, no error, just a wrong salary quietly leaving the system. The WORST kind of bug: the legal one.
Why line 16 is the villain: the class itself is a useful base — C10 proved families need it. The crime is building the idea directly. We don't want to delete DeliveryPartner; we want Java to refuse that one line for us, forever.

THE MOMENT OF NEED — ONE WORD MAKES THE REFUSAL OFFICIAL

THE FIX

Java's keyword for "this class is an idea, not a thing" is abstract. One word, added in front of class — nothing else in the file changes:

abstract class DeliveryPartner
{
... exactly the same fields and method as before ...
}

RECOMPILE — AND NOW THE COMPILER FIGHTS FOR US:

ZeroSalary.java:16: error: DeliveryPartner is abstract; cannot be instantiated DeliveryPartner ghost = new DeliveryPartner(); ^

The intern's line is now impossible to compile. The ₹0.0 salary can never happen again — not because everyone remembered the memo, but because the language enforces it.

DEFINITION — abstract class (write this, word for word)

An abstract class is a class declared with the abstract keyword that cannot be instantiated (​new on it is a compile-time error) and exists to be extended by subclasses. It may contain everything an ordinary class contains — fields, constructors, fully implemented (concrete) methods — and it may additionally declare abstract methods (headings without bodies). Any class that inherits an abstract method and does not implement it must itself be declared abstract; the first subclass that implements them all becomes concrete and instantiable.

Cannot be instantiated

new on an abstract class is a COMPILE error — the exact sentence the compiler printed. This is the definition; you just watched it earn its keep.

Still a proud parent

extends works exactly as in C10. Children of an abstract class are built with new as usual — only the parent itself refuses.

Keeps fields + real methods

An abstract class is NOT empty. name, baseRate and full method bodies all stay — shared by every child, written once.

Still a reference type

DeliveryPartner p = new BikePartner(); stays legal — C10's dispatch still works. Only new DeliveryPartner() died.

PART 4 · THE METHOD THAT REFUSES TO HAVE A BODY

Sometimes the parent knows WHAT — never HOW.

The abstract DeliveryPartner still carries a problem: its calculatePayout() returns a made-up 0.0, because a plain partner honestly has no idea how payouts work — bikes earn per km, walkers per order. The parent knows every child must have this method. It just cannot write the body. Java has a shape for exactly that. Two tiny stories first.

DEFINITION — abstract method (write this, word for word)

An abstract method is a method declared with the abstract keyword that has a signature but NO body — the declaration ends in a semicolon instead of braces: abstract double calculatePayout();. It may appear only inside an abstract class (or an interface). It forces a contract: every concrete subclass MUST override it with a real body, or that subclass must itself be declared abstract. The parent states WHAT must exist; each child supplies HOW.

MICRO PAIR · TWO EVERYDAY STORIES — THE PROMISE, THEN THE PROMISE LIVING NEXT TO REAL CODE

MICRO 3 · every notification pings — differently
abstract class Notification
{
abstract void ping(); // heading only — no braces, just ;
}
class InstaLike extends Notification
{
void ping()
{
System.out.println("someone liked your reel");
}
}
The parent writes the promise — the semicolon where a body should be IS the syntax. The child supplies the ping. That "child method with the parent's exact signature" is C10's overriding — now made compulsory.
MICRO 4 · a promise and real code, side by side
abstract class GameMode
{
abstract int xpEarned(); // each mode decides
void showXP() // shared by ALL modes
{
System.out.println("You earned " + xpEarned() + " XP");
}
}
Abstract and concrete methods coexist. showXP() is written ONCE and already calls xpEarned() — a method that doesn't exist yet! It trusts every future child (RankedMode, CasualMode) to keep the promise. This is the whole power move.

But what makes the promise BINDING? A promise nobody enforces is just a comment. Let's try to cheat: write a child of Notification that quietly "forgets" to write ping() — and see who catches us.

THE CHEAT
abstract class Notification
{
abstract void ping();
}
class MutedApp extends Notification
{
// no ping() here — surely nobody will notice?
}

javac Forgetful.java —

Forgetful.java:6: error: MutedApp is not abstract and does not override abstract method ping() in Notification class MutedApp extends Notification ^

Read the error slowly — it offers the only two legal escapes: override the method, or declare yourself abstract too (pass the promise down to YOUR children). Staying concrete and silent is not on the menu.

THE FIVE RULES — EACH ONE YOU HAVE NOW SEEN HAPPEN

RULEWHAT IT SAYSWHERE YOU SAW IT
No bodyAn abstract method is a signature ending in ; — braces are a compile error.Micro 3, the hot line
Abstract home onlyOne abstract method forces the whole class to be declared abstract.Both micros — parents carry the keyword
Override is compulsoryEvery concrete child MUST override every inherited abstract method.The MutedApp refusal
Or stay abstractA child that doesn't override must itself be abstract — the promise rolls downhill.Named inside the error message
Mixing is allowedAbstract and normal methods, plus fields, live together in one abstract class.Micro 4 — xpEarned() + showXP()
Exam trap — spot the FALSE statement: "An abstract class cannot contain a normal (concrete) method."

FALSE — and Micro 4 is your proof: showXP() has a full body inside abstract GameMode. The true statement points the other way: a class holding even ONE abstract method must be abstract. Examiners love swapping that direction.

PART 5 · SELF-STUDY CARD — READ ONCE AT HOME, 4 MINUTES

When do I make the parent abstract at all?

C10's DeliveryPartner was a plain superclass and life was fine. Today it became abstract and life got safer. Both are legal designs — so which do you reach for? One honest question decides it.

KEEP THE PARENT PLAIN WHEN…

new Parent() makes sense

A plain Vehicle in a parking app is fine if generic "vehicle" records really exist. The parent is a complete thing that children merely extend. C10's world.

MAKE THE PARENT ABSTRACT WHEN…

new Parent() would be a lie

Nothing in reality is only "content", only a game mode, only a plain delivery partner. The parent is a shared idea — real code + real fields, but no honest stand-alone object.

The one-question test: "Could a row in my database honestly be JUST the parent?" If no — abstract.

Self-check before you close the tab: a music app has PremiumUser extends User and FreeUser extends User — and every account is always one or the other, never "just a User". Should User be abstract? (Yes — no honest stand-alone object exists. If someday "plain accounts" become real, the design flips back.)

DON'T TRUST THE PARENTHESES — SETTLE THE SELF-CHECK WITH A RUNNING FILE:

// UserCheck.java — the self-check, proven instead of believed
abstract class User
{
String handle;
abstract String planLabel();
}
class PremiumUser extends User
{
String planLabel()
{
return "Premium plan";
}
}
class FreeUser extends User
{
String planLabel()
{
return "Free plan";
}
}
public class UserCheck
{
public static void main(String[] args)
{
// User ghost = new User(); — un-comment it and javac refuses: "User is abstract; cannot be instantiated"
User a = new PremiumUser();
User b = new FreeUser();
a.handle = "@zoya_edits";
b.handle = "@rohan.lofi";
System.out.println(a.handle + " holds the " + a.planLabel());
System.out.println(b.handle + " holds the " + b.planLabel());
}
}

C:\...\class-11> javac UserCheck.java

(clean — every account is a real child)

C:\...\class-11> java UserCheck

@zoya_edits holds the Premium plan

@rohan.lofi holds the Free plan

PART 6 · WORKED EXAMPLE — EVERYTHING SO FAR, ONE HONEST FILE

The spine: one idea, two real children, one payroll.

You already own every piece of this file: the abstract parent (Part 3), the abstract method + compulsory override (Part 4), and C10's dispatch. Nothing new is introduced here — that is the point of a worked build. Assemble it floor by floor.

THE ASSEMBLY PLAN — ONE PIECE PER PRESS · REAL UML, EVERY EDGE ACTUALLY DRAWN

«abstract» DeliveryPartner name + deliveries + goOnDuty() shared · calculatePayout() only PROMISED extends TopRatedDeliveryPartner keeps the promise · Rs. 45/delivery BikePartner keeps the promise · Rs. 32/delivery

Both children hang off ONE drawn edge into the hollow triangle — the UML way of writing "IS-A". Same question — "your payout?" — two honest answers. The parent never had to guess.

SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\diya\Desktop\java-practice\class-11\Spine11.java
Spine11.java — THE PART-E SPINE, TYPED LIVE
1abstract class DeliveryPartner
2{
3 String name;
4 int deliveries;
5
6 void goOnDuty()
7 {
8 System.out.println(name + " is on duty");
9 }
10
11 abstract double calculatePayout(); // the promise
12}
13
14class TopRatedDeliveryPartner extends DeliveryPartner
15{
16 TopRatedDeliveryPartner(String partnerName, int done)
17 {
18 name = partnerName; // inherited field, plainly assigned
19 deliveries = done;
20 }
21
22 double calculatePayout() // promise kept
23 {
24 return deliveries * 45.0;
25 }
26}
27
28class BikePartner extends DeliveryPartner
29{
30 BikePartner(String partnerName, int done)
31 {
32 name = partnerName;
33 deliveries = done;
34 }
35
36 double calculatePayout() // promise kept — its own way
37 {
38 return deliveries * 32.0;
39 }
40}
41
42public class Spine11
43{
44 public static void main(String[] args)
45 {
46 DeliveryPartner meera = new TopRatedDeliveryPartner("Meera", 10);
47 DeliveryPartner arjun = new BikePartner("Arjun", 10);
48 meera.goOnDuty();
49 arjun.goOnDuty();
50 System.out.println("Meera earns Rs. " + meera.calculatePayout());
51 System.out.println("Arjun earns Rs. " + arjun.calculatePayout());
52 }
53}
TERMINAL — PREDICT ALL FOUR LINES FIRST
C:\...\class-11> javac Spine11.java
(clean — every promise is kept)
C:\...\class-11> java Spine11
Meera is on duty
Arjun is on duty
Meera earns Rs. 450.0
Arjun earns Rs. 320.0
Both variables are typed DeliveryPartner — the abstract idea — yet each payout ran the child's honest body. C10's dispatch + today's compulsory promise, working together.
Notice what is NOT in this file: no this, no super. The constructor parameter is named partnerName, so the inherited field name is assigned plainly — no name clash, no ceremony. Reach for those keywords only when a real clash or a parent constructor genuinely demands them (C10 showed the demanding cases).

PART 7 · ACTIVITY 1 — NOTEBOOKS OUT · DESIGN, NO CODE

Your own OTT subscription is an abstract class in disguise.

THE SCENE Spotify Student. Netflix Mobile. Prime Student. Every plan you actually pay for is a specific plan — nobody on earth subscribes to "a plan" in general. Sound familiar? That is exactly the Content/Reel gap from Part 3.

YOUR TASK In your notebook — signatures and sentences only, no method bodies:

  • Write the class heading for an abstract class named SubscriptionPlan.
  • Give it ONE field every plan genuinely shares (pick your own — think of what appears on every bill).
  • Write the heading of ONE abstract method renewalPrice() that returns a double — remember how an abstract method ends.
  • Write the class heading of ONE concrete child, named after a real plan you or a friend pays for.
  • Finish with one sentence: why must SubscriptionPlan stay abstract?

Attempt all five in the notebook first — the sheet stays locked until you do.

SOLUTION SHEET · ACTIVITY 1 — ONE HONEST DESIGN (YOURS MAY DIFFER)
// PlanCheck.java — the notebook design, promoted to a file that RUNS
abstract class SubscriptionPlan
{
String planHolder = "Aarav"; // on every bill
abstract double renewalPrice(); // heading + semicolon — NO braces
}
class SpotifyStudent extends SubscriptionPlan
{
double renewalPrice() // the promise, KEPT — Part 4's rule
{
return 59.0;
}
}
public class PlanCheck
{
public static void main(String[] args)
{
SubscriptionPlan mine = new SpotifyStudent();
System.out.println(mine.planHolder + " pays Rs. " + mine.renewalPrice());
}
}

TYPE IT, COMPILE IT, RUN IT — THE DESIGN MUST SURVIVE A REAL TERMINAL:

C:\...\class-11> javac PlanCheck.java

(clean — the child kept the promise)

C:\...\class-11> java PlanCheck

Aarav pays Rs. 59.0

  • MARK 1abstract sits before class — position matters, it is part of the heading.
  • MARK 2abstract double renewalPrice(); — the semicolon IS the "no body" syntax. Braces here would be a compile error.
  • MARK 3The why-sentence full-marks shape: "No customer ever holds a plain SubscriptionPlan — only specific plans exist, so building the idea directly must be forbidden."
  • WHY THE BODYYour notebook answer carries headings only — but the sheet ships the COMPILING version, because a concrete SpotifyStudent without renewalPrice() refuses to compile (Part 4's rule). A solution that cannot run is an idea, not a solution.

PART 8 · ACTIVITY 2 — ERROR DETECTION · READ LIKE A COMPILER

A teammate "just wants a quick test object."

THE SCENE Your Activity-1 design got merged. A teammate writing a quick test types this and hits compile:

public class QuickTest
{
public static void main(String[] args)
{
SubscriptionPlan p = new SubscriptionPlan();
System.out.println(p.renewalPrice());
}
}

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

  • Which line refuses to compile — and quote the compiler's exact key phrase from memory.
  • Explain WHY Java must refuse, in one sentence that mentions renewalPrice().
  • Fix the test WITHOUT touching SubscriptionPlan itself — what is the one-line change?
  • Bonus: is the left side of the assignment (SubscriptionPlan p) also illegal? Careful…

Four written answers first. The bonus catches half the room.

SOLUTION SHEET · ACTIVITY 2
  • Q1The hot line. Key phrase: SubscriptionPlan is abstract; cannot be instantiated — the same sentence ZeroSalary produced in Part 3.
  • Q2Full-marks shape: "If Java built the object, p.renewalPrice() would have NO body to run — the class only promises the method, it never wrote it." The refusal protects the very next line.
  • Q3Build a real child instead: SubscriptionPlan p = new SpotifyStudent(); — one line, the parent file untouched.
  • BONUSThe left side is perfectly legal. An abstract type as a REFERENCE is normal and useful — that is how Spine11's meera and arjun were declared. Only new SubscriptionPlan() — the right side — is the crime.

PROOF 1 — THE MERGED FILE EXACTLY AS THE TEAMMATE COMPILED IT (Activity-1 classes above the test):

// QuickTest.java — teammate's "quick test object" at the bottom
abstract class SubscriptionPlan
{
abstract double renewalPrice();
}
class SpotifyStudent extends SubscriptionPlan
{
double renewalPrice()
{
return 59.0;
}
}
public class QuickTest
{
public static void main(String[] args)
{
SubscriptionPlan p = new SubscriptionPlan(); // the crime — line 19
System.out.println(p.renewalPrice());
}
}

QuickTest.java:19: error: SubscriptionPlan is abstract; cannot be instantiated SubscriptionPlan p = new SubscriptionPlan(); ^ 1 error

PROOF 2 — THE ONE-LINE FIX, THEN A REAL RUN (everything else untouched):

// QuickTest.java — same file, line 19 repaired
abstract class SubscriptionPlan
{
abstract double renewalPrice();
}
class SpotifyStudent extends SubscriptionPlan
{
double renewalPrice()
{
return 59.0;
}
}
public class QuickTest
{
public static void main(String[] args)
{
SubscriptionPlan p = new SpotifyStudent(); // a real child — parent file untouched
System.out.println(p.renewalPrice());
}
}

C:\...\class-11> javac QuickTest.java

(clean)

C:\...\class-11> java QuickTest

59.0

PART 9 · A PROBLEM extends CANNOT SOLVE

Finance wants ONE promise from three unrelated families.

New requirement lands: "Anything the app pays — delivery partners, restaurant vendors, refunded customers — must expose one uniform method, so payroll can treat them all alike." Three families. No shared parent. Watch both of our existing tools fail before the new one appears.

TWO DEAD-ENDS — WHY YESTERDAY'S TOOLBOX IS NOT ENOUGH

DEAD-END 1

"Make them all extend one abstract Payable class." But Vendor already extends Business, and Java allows exactly ONE parent per class (C10's single-inheritance law). Forcing three unrelated families under one parent would also invent a fake IS-A: a refunded customer IS-A payable-thing? That is a job description, not an identity.

DEAD-END 2

"Just tell everyone to write the same method." A team memo is Part 4's unenforced promise all over again — one renamed method (getPayout() vs payableAmount()) and payroll breaks at 2 a.m. with no compiler on our side. We NEED the enforcement, without demanding a shared parent.

The moment of need: we want a pure contract — a bundle of promises with no fields to inherit, no bodies to share, no parent slot consumed. Java's name for that is interface. A class doesn't extend a contract, it signs it: implements.

DEFINITION — interface (write this, word for word)

An interface is a fully abstract reference type declared with the interface keyword: a named collection of method signatures (all implicitly public abstract) and constants (all implicitly public static final), with no instance fields and no constructors. A class signs the contract with implements and must then provide public bodies for every promised method. Because an interface consumes no parent slot, one class may implement MANY interfaces (comma-separated) while still extending one class — this is how Java delivers what multiple inheritance promised, without the diamond.

MICRO PAIR · THE SMALLEST CONTRACT EVER SIGNED — AND WHAT SIGNING COSTS

MICRO 5 · a contract + one honest signer
interface Shareable
{
void share(); // promise — no body, like Part 4
}
class Meme implements Shareable
{
public void share()
{
System.out.println("sent to the group chat");
}
}
Two new words, one old idea. interface replaces abstract class; implements replaces extends. The promise-keeping duty is EXACTLY Part 4's rule.
MICRO 6 · the public trap — every fresher hits it
class Story implements Shareable
{
void share() // forgot 'public' — watch
{
System.out.println("added to your story");
}
}
Refused: "attempting to assign weaker access privileges; was public." Interface methods are public by default — so every keeper must say public out loud. C10's no-narrowing law, resurfacing.

Scale the micro up: the finance contract is Payable with one promise — double payableAmount(). Here it is signed by Vendor, a class from a completely different family. Predict the payout line.

SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\diya\Desktop\java-practice\class-11\FirstContract.java
FirstContract.java — YOUR FIRST SIGNED CONTRACT
1interface Payable
2{
3 double payableAmount(); // public + abstract, automatically
4}
5
6class Vendor implements Payable
7{
8 int ordersServed = 50;
9
10 public double payableAmount() // public — Micro 6's lesson
11 {
12 return ordersServed * 250.0;
13 }
14}
15
16public class FirstContract
17{
18 public static void main(String[] args)
19 {
20 Payable p = new Vendor(); // contract as reference type!
21 System.out.println("Owed: Rs. " + p.payableAmount());
22 }
23}
TERMINAL
C:\...\class-11> javac FirstContract.java
(clean)
C:\...\class-11> java FirstContract
Owed: Rs. 12500.0
Line 20 is the payoff: Payable p — a variable typed by a CONTRACT, not a class. Payroll can now hold anything that signed, without knowing its family. Also note: new Payable() would refuse exactly like an abstract class.
Say the two rules once: inside an interface, methods are public abstract without writing it. Keepers must write public themselves — narrowing is refused. Everything else you already knew from Part 4.

PART 10 · THE COMPARISON EVERY INTERVIEW ASKS

Two refusals, one table — every row has a reason you watched.

You now hold BOTH tools. Neither can be built with new — but they refuse for different reasons and shine in different jobs. This table is the single most-asked comparison in Java interviews; today every row is a memory, not a memorisation.

QUESTIONABSTRACT CLASSINTERFACE
Keyword pairabstract class + extendsinterface + implements
How many can a class take?ONE parent — single inheritanceMANY contracts — comma-separated
Instance fields?Yes — name, deliveries lived in Spine11No — only public static final constants
Method bodies?Yes — goOnDuty() had oneClassically none (Java-8 note next part)
Constructors?Yes — run via the child's chainNever — nothing to initialise
Default access of methodsPackage-private unless statedpublic automatically — Micro 6's trap
Relationship it modelsIS-A — identity ("a bike partner IS a delivery partner")CAN-DO — capability ("a vendor CAN be paid")

THE 5-SECOND DECISION — WHICH DO I REACH FOR?

REACH FOR abstract class WHEN…

shared FIELDS or shared BODIES exist

The family owns state and common code — name, deliveries, a ready goOnDuty(). You are building the TRUNK of one family tree.

REACH FOR interface WHEN…

only a PROMISE must cross families

No state, no bodies — just "everyone answers this question". Payable cut across partners, vendors AND customers without touching their parents.

Interview phrasing that wins: "abstract class shares implementation, interface shares expectation."

Say it with the IS-A vs CAN-DO row and you have answered the question completely — in two sentences.

PART 11 · SELF-STUDY CARD — A 3-LINE PREVIEW, NOTHING MORE

One asterisk on the table — parked, on purpose.

The three lines: (1) Since Java 8, an interface MAY carry a method body if it is marked default or static. (2) This exists so old interfaces can gain new methods without breaking every signer in the world. (3) The full treatment — rules, clashes, when-to-use — is core material at Class 16; nothing before then requires it.

Why we park it: today's mental model — "interface = pure promise" — is the one the exam table and every classification question rely on. Learn the exception AFTER the rule is muscle memory. If it appears in a question bank early, you now know its name and its home.

PART 12 · THE COMMA THAT extends NEVER EARNED

One person. Three hats. All legal.

C10 taught the hard law: ONE parent, ever — class A extends B, C is refused. Contracts play by a friendlier rule, because signing a promise consumes nothing. Watch the same delivery partner put on three hats, one per press.

THE CONTRACT DIAGRAM — ONE HAT PER PRESS, THEN THE INK: DASHED EDGES ARE THE SIGNATURES

«interface» Payable «interface» Trackable «interface» Rateable TopRatedDeliveryPartner one class · parent slot still untouched implements ×3

Three dashed edges from ONE class — all legal, because dashed means "signed a contract", not "IS-A". Hats are jobs, not identities: you can hold many jobs, you can only be one person.

Micro first — the smallest triple-signing that can exist: before the full file, just the heading and what it owes. Count the debts: three contracts × one promise each = three public methods due.

MICRO 7 · the legal comma, heading only
class Partner implements Payable, Trackable, Rateable
{
// owes: payableAmount() + currentZone() + addStars()
// miss ANY one -> Part 4's "does not override" refusal
}
The comma lives after implements — never after extends. Each contract adds duties, not fields, so no diamond confusion is possible.
CONTRAST · the comma that is still refused
class Partner extends Person, Employee // NO.
{
}
Unchanged from C10. Two parents could both bring a field called name WITH state — whose value wins? Java refuses the ambiguity at the parent level, and allows it at the promise level.
SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\diya\Desktop\java-practice\class-11\ThreeHats.java
ThreeHats.java — ALL THREE DEBTS, PAID
1interface Payable
2{
3 double payableAmount();
4}
5
6interface Trackable
7{
8 String currentZone();
9}
10
11interface Rateable
12{
13 void addStars(int stars);
14}
15
16class Partner implements Payable, Trackable, Rateable
17{
18 int deliveries = 10;
19 int totalStars = 0;
20
21 public double payableAmount()
22 {
23 return deliveries * 45.0;
24 }
25
26 public String currentZone()
27 {
28 return "Banjara Hills";
29 }
30
31 public void addStars(int stars)
32 {
33 totalStars = totalStars + stars;
34 }
35}
36
37public class ThreeHats
38{
39 public static void main(String[] args)
40 {
41 Partner ravi = new Partner();
42 Payable forFinance = ravi; // finance sees ONE hat only
43 Trackable forMaps = ravi; // maps sees another
44 System.out.println("Owed: Rs. " + forFinance.payableAmount());
45 System.out.println("Zone: " + forMaps.currentZone());
46 }
47}
TERMINAL
C:\...\class-11> javac ThreeHats.java
(clean — all three debts paid)
C:\...\class-11> java ThreeHats
Owed: Rs. 450.0
Zone: Banjara Hills
Lines 42–43: the SAME object, seen through two different hats. forFinance can ONLY call payableAmount() — try forFinance.currentZone() and the compiler refuses. Each contract is a window that shows exactly its own promises.
Style discipline, no exceptions: even a one-promise interface gets its braces on their own lines — the same Allman shape as every class and method in this course. One consistent shape means your eyes never re-learn how to scan a file.

ADD-ON · THE HALF-KEPT CONTRACT — WHEN A CLASS CANNOT PAY EVERY DEBT

Can't implement them all yet? Then SAY so: abstract.

ThreeHats paid all three debts in one class. Real sprints are messier — sometimes a module isn't ready and one promise must wait. Java gives you exactly one honest way out, and it is a keyword you already own.

Week one of the food app: the GPS module ships next sprint, so currentZone() simply cannot be written yet. A teammate signs both contracts anyway and pays only one. Predict the compiler's verdict before the terminal shows it.

HalfBroken.java — TWO CONTRACTS SIGNED, ONE DEBT PAID
1interface Payable
2{
3 double payableAmount();
4}
5
6interface Trackable
7{
8 String currentZone();
9}
10
11class WeekOnePartner implements Payable, Trackable
12{
13 public double payableAmount()
14 {
15 return 300.0;
16 }
17 // currentZone() NOT written — GPS module lands next sprint
18}
TERMINAL — THE COMPILER COUNTS THE DEBTS
C:\...\class-11> javac HalfBroken.java
HalfBroken.java:11: error: WeekOnePartner is not abstract and does not
override abstract method currentZone() in Trackable
class WeekOnePartner implements Payable, Trackable
^
1 error
Read it slowly — the compiler names BOTH exits in one sentence: either the class overrides the missing method, or the class is abstract. There is no third door.
Why line 11 takes the blame: that heading signs TWO contracts, so the class owes two public bodies. Only one arrived. The compiler charges the signature line — the promise — not the missing method.

The honest week-one design: the class declares its unpaid debt with abstract, and the promise rolls forward until a child finally pays it — Part 4's pass-it-down rule, now crossing a contract.

SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\diya\Desktop\java-practice\class-11\HalfHats.java
HalfHats.java — THE DEBT DECLARED, THEN SETTLED BY A CHILD
1interface Payable
2{
3 double payableAmount();
4}
5
6interface Trackable
7{
8 String currentZone();
9}
10
11abstract class WeekOnePartner implements Payable, Trackable
12{
13 public double payableAmount()
14 {
15 return 300.0;
16 }
17 // currentZone() stays owed — abstract makes the debt official
18}
19
20class GpsPartner extends WeekOnePartner
21{
22 public String currentZone() // sprint two: the last debt, paid
23 {
24 return "Madhapur";
25 }
26}
27
28public class HalfHats
29{
30 public static void main(String[] args)
31 {
32 Payable forFinance = new GpsPartner();
33 Trackable forMaps = new GpsPartner();
34 System.out.println("Owed: Rs. " + forFinance.payableAmount());
35 System.out.println("Zone: " + forMaps.currentZone());
36 }
37}
TERMINAL — EVERY PROMISE NOW HAS AN OWNER
C:\...\class-11> javac HalfHats.java
(clean — the debt is declared, then settled)
C:\...\class-11> java HalfHats
Owed: Rs. 300.0
Zone: Madhapur
Line 11 is the whole lesson: abstract + implements in one heading — "I sign both contracts, I pay one now, my children owe the rest." GpsPartner pays the last debt and becomes the family's first buildable class.
Notice what did NOT change: both interfaces are untouched between the broken and fixed files. The fix lives entirely on line 11 — one keyword that turns an accusation into a declared plan.
RULE — write this, word for word

A class that implements an interface but does not provide bodies for ALL of its methods must itself be declared abstract. The unimplemented promises pass down to its subclasses, and the first subclass that implements every remaining method becomes concrete and instantiable — the same chain rule you learnt for abstract methods in Part 4, now crossing a contract.

ADD-ON · THE DIAMOND PROBLEM — WHY THE COMMA IS SAFE HERE AND POISON AFTER extends

Two parents, one method, whose body wins? Interfaces make the question disappear.

The contrast card above said "no diamond confusion is possible" — now EARN that sentence. First watch the diamond actually refuse with classes, then watch the interface version dissolve it in a real run.

Draw the shape first: ONE grandparent at the top, TWO parents in the middle who both inherit perform(), ONE student at the bottom who inherits from both parents. Top → two sides → bottom: the four boxes form a diamond ◇. The question the shape asks: when the student calls perform(), whose copy travels down — the left parent's or the right parent's?

THE DIAMOND, POSED WITH CLASSES — WHY JAVA SLAMS THIS DOOR

FestDiamond.java — TWO PARENT CLASSES, TWO WORKING BODIES
1class Performer // the TOP of the diamond
2{
3 void perform()
4 {
5 System.out.println("On stage");
6 }
7}
8
9class Guitarist extends Performer // LEFT side — overrides
10{
11 void perform()
12 {
13 System.out.println("Guitar riff");
14 }
15}
16
17class Dancer extends Performer // RIGHT side — overrides too
18{
19 void perform()
20 {
21 System.out.println("Hip-hop steps");
22 }
23}
24
25class FestStudent extends Guitarist, Dancer // the BOTTOM — whose perform()?
26{
27}
TERMINAL — REFUSED AT THE GRAMMAR LEVEL
C:\...\class-11> javac FestDiamond.java
FestDiamond.java:25: error: '{' expected
class FestStudent extends Guitarist, Dancer
^
1 error
Two overriding bodies exist (lines 11–14 and 19–22). If line 25 were legal, student.perform() would have no honest answer. Java refuses so hard the comma after extends does not even PARSE — the diamond question can never be asked with classes.
The diamond in one look: Performer at the top, Guitarist and Dancer as the two sides, FestStudent at the bottom. Two DIFFERENT working bodies for the same method would arrive at the bottom simultaneously — that ambiguity IS the diamond problem.

THE SAME DIAMOND, REDRAWN WITH INTERFACES — WATCH IT DISSOLVE IN A REAL RUN

Same four boxes, new material: the top is now a contract, the two sides are contracts that extends it (yes — an interface may extend an interface), and the bottom is ONE class signing both sides. The shape is identical. The ambiguity is gone — because contracts carry promises, never bodies: three copies of the same promise merge into ONE debt.

SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\diya\Desktop\java-practice\class-11\TwoClubs.java
TwoClubs.java — THE FULL DIAMOND, ALL PROMISES, ONE BODY
1interface Performer // TOP of the diamond — the shared promise
2{
3 void perform();
4}
5
6interface MusicClub extends Performer // LEFT side — inherits the promise
7{
8 void perform(); // re-states it — still just a promise, NO body
9}
10
11interface DanceClub extends Performer // RIGHT side — inherits it too
12{
13 void perform(); // the THIRD copy of the same promise
14}
15
16class FestStudent implements MusicClub, DanceClub // BOTTOM — both sides signed
17{
18 public void perform() // ONE body settles ALL THREE copies
19 {
20 System.out.println("Mashup set: guitar + footwork");
21 }
22}
23
24public class TwoClubs
25{
26 public static void main(String[] args)
27 {
28 FestStudent zara = new FestStudent();
29 MusicClub onStageA = zara; // through the LEFT side
30 DanceClub onStageB = zara; // through the RIGHT side
31 Performer onTop = zara; // even through the TOP
32 onStageA.perform();
33 onStageB.perform();
34 onTop.perform();
35 }
36}
TERMINAL — ALL THREE WINDOWS, ONE BODY
C:\...\class-11> javac TwoClubs.java
(clean — three copies of one promise merged into one debt)
C:\...\class-11> java TwoClubs
Mashup set: guitar + footwork
Mashup set: guitar + footwork
Mashup set: guitar + footwork
The same line three times — left window, right window, top window — because in the whole diamond only ONE body exists (line 18). Nothing to duplicate, nothing to choose between: the shape survives, the problem doesn't.
Line 6 and line 11 quietly teach a bonus rule: an interface extends another interface with extends (not implements) — and unlike classes, an interface may even extend SEVERAL interfaces. Contracts stack safely at every level, for the same reason: no bodies, no state, no fights.
EXAM SENTENCE — how interfaces solve the diamond problem

The diamond problem: a common ancestor at the top, two middle types that each inherit (and override) the same method, and one bottom type inheriting from both — so two implementations (bodies + state) of one method would reach the bottom, and no call could honestly pick one. Java forbids multiple class inheritance outright (the comma after extends does not even parse) and allows the SAME diamond drawn with interfaces, because interfaces contribute only method signatures — no bodies, no instance state. However many paths the promise travels down (top, left, right), the copies merge into a single obligation, and the implementing class's ONE public body satisfies them all — nothing exists to be ambiguous.

PART 13 · WORKED EXAMPLE — THE FINANCE TEAM GETS ITS WISH

One queue. Three families. Zero special cases.

Part 9 opened with finance's demand: pay partners, vendors and refunded customers through one uniform door. Every tool is now in hand. Watch the payoff: a single Payable[] array holds all three families, and one loop pays everyone — payroll never asks "which family are you from?"

SAVE AS · EXACT NAME, EXACT FOLDER C:\Users\diya\Desktop\java-practice\class-11\Payday.java
Payday.java — ONE DOOR, EVERYONE PAID
1interface Payable
2{
3 double payableAmount();
4}
5
6class Partner implements Payable
7{
8 int deliveries = 10;
9
10 public double payableAmount()
11 {
12 return deliveries * 45.0;
13 }
14}
15
16class Vendor implements Payable
17{
18 int ordersServed = 50;
19
20 public double payableAmount()
21 {
22 return ordersServed * 250.0;
23 }
24}
25
26class RefundedCustomer implements Payable
27{
28 double refundDue = 320.0;
29
30 public double payableAmount()
31 {
32 return refundDue;
33 }
34}
35
36public class Payday
37{
38 public static void main(String[] args)
39 {
40 Payable[] queue = { new Partner(), new Vendor(), new RefundedCustomer() };
41 double total = 0.0;
42
43 for (Payable p : queue)
44 {
45 total = total + p.payableAmount(); // no family check, ever
46 }
47
48 System.out.println("Total paid out: Rs. " + total);
49 }
50}
TERMINAL — DO THE MATHS IN THE NOTEBOOK FIRST
C:\...\class-11> javac Payday.java
(clean)
C:\...\class-11> java Payday
Total paid out: Rs. 13270.0
450 + 12500 + 320 = 13270. Add a fourth family tomorrow? Write its class, have it sign Payable — the LOOP NEVER CHANGES. That sentence is why interfaces exist.
Line 40's braces are an array initialiser, not a code block — Java's one legitimate inline brace pair, listing the queue's three members. Every METHOD body in this file keeps its braces on their own lines, as always.

Pause and look back: Part 3's compiler refused a dishonest object. Part 13's compiler guaranteed that three honest strangers answer one question. Refusal and guarantee are the same power — the type system working for you, before the program ever runs.

PART 14 · ACTIVITY 3 — ERROR DETECTION · READ LIKE A COMPILER

A helpful teammate "improves" the contract.

THE SCENE A teammate on Java 7 tooling decides the Payable contract should "help" its signers by including a ready-made body:

interface Payable
{
double payableAmount()
{
return 0.0; // "a sensible default", says the teammate
}
}

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

  • Does this compile under classic (pre-Java-8) interface rules? One word, then the reason.
  • Predict the compiler's complaint — which part of the method is the problem, the heading or the body?
  • Explain to the teammate WHY the language forbids it — use the word "promise" or "contract" in your sentence.
  • Bonus: the teammate's return 0.0; default — where have you seen a "default 0.0" cause real damage today?

Four lines in the notebook before the sheet opens.

SOLUTION SHEET · ACTIVITY 3
  • Q1No. Classic interface methods are implicitly abstract — and an abstract method with a body is a contradiction the compiler rejects.
  • Q2The BODY. The message reads: interface abstract methods cannot have body — the heading alone was perfectly legal.
  • Q3Full-marks shape: "An interface IS the contract, not a worker — the moment it carries working code, signers can silently inherit behaviour nobody promised, and the contract stops being pure."
  • BONUSPart 3's ZeroSalary — a "sensible default" of 0.0 is exactly the quiet wrong-salary bug that made us reach for abstract in the first place. Defaults that lie are worse than refusals.
  • HONEST FOOTNOTEJava 8's default keyword (Part 11's parked card) makes a marked version of this legal — with new rules, taught properly at Class 16. Unmarked bodies remain illegal in every Java.

PROOF 1 — THE TEAMMATE'S FILE EXACTLY AS PUSHED, AND THE COMPILER'S VERDICT:

// Payable.java — the "improved" contract
interface Payable
{
double payableAmount()
{
return 0.0; // "a sensible default", says the teammate
}
}

Payable.java:4: error: interface abstract methods cannot have body double payableAmount() ^ 1 error

PROOF 2 — THE CONTRACT RESTORED + A SIGNER + A RUN, ONE COMPLETE FILE:

// ContractCheck.java — pure contract, honest keeper, real payout
interface Payable
{
double payableAmount(); // heading + semicolon — the contract stays pure
}
class Vendor implements Payable
{
int ordersServed = 40;
public double payableAmount() // public — Micro 6's lesson
{
return ordersServed * 250.0;
}
}
public class ContractCheck
{
public static void main(String[] args)
{
Payable p = new Vendor();
System.out.println("Owed: Rs. " + p.payableAmount());
}
}

C:\...\class-11> javac ContractCheck.java

(clean — the contract is pure again)

C:\...\class-11> java ContractCheck

Owed: Rs. 10000.0

PART 15 · ACTIVITY 4 — THE DESIGNER'S CHAIR · SIX VERDICTS

Abstract class or interface? Six real briefs, you decide.

THE RULE OF THUMB You built it in Part 10 — shared fields/bodies call for an abstract class (IS-A trunk); a promise crossing unrelated families calls for an interface (CAN-DO hat). Write six verdicts in the notebook, each with a one-line reason, BEFORE revealing any answer.

  • A payment gateway must support Cards, Net-Banking, and Wallets — each processes a payment completely differently, and they share no stored data.
  • Every SocialMediaPost — text, photo, reel — must carry a timestamp, and the getTimestamp() logic is IDENTICAL for all of them.
  • The Payable promise must be enforced across DeliveryPartner, Vendor and Customer — three families with three different parents.
  • Your Class-1 flatmate expense register grows up: every tracker variant shares the members list and the add-expense code, but splits the bill differently.
  • An AttendanceCalculator needs only ONE thing shared: everyone answers compute(). No common fields, no common code.
  • A Notifier family — SMS, email, push — must all send, and the team wants a shared retry counter and shared logging code in one place.

Six verdicts + six reasons in the notebook first. Two of them trap the hasty.

SOLUTION SHEET · ACTIVITY 4 — SIX VERDICTS
1 · Payment gateway — Cards / Net-Banking / Wallets
No shared state, no shared code — only the promise "process a payment". A pure contract crossing unrelated providers.
INTERFACE
2 · SocialMediaPost with identical getTimestamp()
Shared WORKING CODE is the giveaway — write getTimestamp() once in the trunk; children inherit it. An interface could not carry that body.
ABSTRACT CLASS
3 · Payable across DeliveryPartner / Vendor / Customer
Three families, three different parents — only a contract can cross them. You RAN this design in Payday.java.
INTERFACE
4 · ExpenseTracker — shared members list + add-expense code
Shared FIELD (the list) + shared BODY (add-expense) + one varying method (the split) — the textbook abstract-class shape, with the split as the abstract method.
ABSTRACT CLASS
5 · AttendanceCalculator — only compute() shared, no state
"No common fields, no common code" is the interface sentence verbatim — one promise, nothing else.
INTERFACE
6 · Notifier — SMS / email / push + shared retry counter + shared logging
The trap twin of #5: the moment a shared FIELD (retry counter) and shared CODE (logging) appear, the interface door closes. send() stays abstract inside the trunk.
ABSTRACT CLASS

Scenarios 5 and 6 are the same domain with ONE line changed — state and shared code flipped the verdict. That single observation IS the exam answer.

PROOF IN CODE — THE FLIP, AS TWO COMPLETE RUNNING FILES. FIRST, SCENARIO 5 (INTERFACE):

// AttendanceCheck.java — one promise, no state, no shared code → interface
interface AttendanceCalculator
{
double compute();
}
class TheoryAttendance implements AttendanceCalculator
{
public double compute()
{
return 42.0 / 50.0 * 100.0; // classes attended / held
}
}
class LabAttendance implements AttendanceCalculator
{
public double compute()
{
return 12.0 / 12.0 * 100.0;
}
}
public class AttendanceCheck
{
public static void main(String[] args)
{
AttendanceCalculator theory = new TheoryAttendance();
AttendanceCalculator lab = new LabAttendance();
System.out.println("Theory: " + theory.compute() + "%");
System.out.println("Lab: " + lab.compute() + "%");
}
}

C:\...\class-11> javac AttendanceCheck.java

(clean)

C:\...\class-11> java AttendanceCheck

Theory: 84.0%

Lab: 100.0%

NOW SCENARIO 6 — SAME DOMAIN, BUT A SHARED FIELD + SHARED CODE APPEAR (ABSTRACT CLASS):

// NotifierCheck.java — shared retry counter + shared logging → abstract class
abstract class Notifier
{
int retryCount = 3; // the shared FIELD an interface cannot hold
void log(String channel) // the shared CODE an interface cannot carry
{
System.out.println(channel + " sent, retries left: " + retryCount);
}
abstract void send(); // only the delivery differs
}
class SmsNotifier extends Notifier
{
void send()
{
log("SMS"); // inherited body, called plainly — no ceremony
}
}
class PushNotifier extends Notifier
{
void send()
{
log("Push");
}
}
public class NotifierCheck
{
public static void main(String[] args)
{
Notifier a = new SmsNotifier();
Notifier b = new PushNotifier();
a.send();
b.send();
}
}

C:\...\class-11> javac NotifierCheck.java

(clean)

C:\...\class-11> java NotifierCheck

SMS sent, retries left: 3

Push sent, retries left: 3

PART 16 · WHAT YOU NOW OWN

Two keywords in, the whole design conversation opens.

YOU CAN NOW…BECAUSE…PROOF FILE
Forbid a dishonest objectabstract class makes new a compile error on the ideaZeroSalary.java
Force a method's existencean abstract method must be overridden or passed downthe MutedApp refusal
Mix promise with real codeabstract + concrete members coexist in one trunkSpine11.java
Cut a promise across familiesinterface + implements consume no parent slotFirstContract.java
Stack many capabilitiesthe comma after implements is legal — hats, not identitiesThreeHats.java
Pay strangers through one doora contract-typed array + dispatch = zero special casesPayday.java
YOUR GROWING PRACTICE FOLDER — SAME ROOT SINCE LAB 0
Desktop\java-practice\
class-10\ — FirstFamily, Spine, Vehicle/Car … (last class)
class-11\
ZeroSalary.java — the ₹0 bug, then the refusal
Spine11.java — abstract parent, two honest children
FirstContract.java — Payable signed by Vendor
ThreeHats.java — one class, three contracts
HalfHats.java — half-kept contract → abstract, child settles it
TwoClubs.java — the diamond, dissolved by two contracts
Payday.java — one queue pays three families
MyPlans.java — tonight's homework, below

HOMEWORK — DUE BEFORE CLASS 12

MyPlans.java Turn your Activity-1 notebook design into a running file. Requirements, one per line:

  • Type your abstract SubscriptionPlan with the field you chose and the abstract renewalPrice().
  • Write TWO concrete plan children from your real life — each keeping the promise with its true monthly price.
  • In main, declare both through a SubscriptionPlan reference — Spine11's pattern.
  • Print each renewal price, then the total you actually pay per month (brace yourself).
  • Add ONE comment line above the class stating why it must stay abstract — your Activity-1 sentence, now living in code.

Open only AFTER your file runs — or refuses in a way you cannot explain.

SOLUTION SHEET · HOMEWORK — ONE HONEST VERSION
// abstract: nobody subscribes to "a plan" — only to specific plans
abstract class SubscriptionPlan
{
String planHolder = "Diya";
abstract double renewalPrice();
}
class SpotifyStudent extends SubscriptionPlan
{
double renewalPrice()
{
return 59.0;
}
}
class NetflixMobile extends SubscriptionPlan
{
double renewalPrice()
{
return 149.0;
}
}
public class MyPlans
{
public static void main(String[] args)
{
SubscriptionPlan music = new SpotifyStudent();
SubscriptionPlan video = new NetflixMobile();
System.out.println("Music: Rs. " + music.renewalPrice());
System.out.println("Video: Rs. " + video.renewalPrice());
System.out.println("Monthly total: Rs. " + (music.renewalPrice() + video.renewalPrice()));
}
}

THE FILE MUST SURVIVE BOTH COMMANDS BEFORE YOU SLEEP:

C:\...\class-11> javac MyPlans.java

(clean — both promises kept)

C:\...\class-11> java MyPlans

Music: Rs. 59.0

Video: Rs. 149.0

Monthly total: Rs. 208.0

  • CHECK 1The terminal above is the target SHAPE — your prices will differ; the three-line structure must not.
  • CHECK 2No this, no super, no constructors — none were needed. Ceremony only where the design demands it.
  • CHECK 3Every brace on its own line — including inside the children. The habit IS the deliverable.