LAB 2 · OPENER
Today your code moves into a real workshop.
Until now you typed Java in Notepad++ and ran it from the command prompt — and that was the right way to learn what javac and java really do. Today you graduate: you'll install Eclipse, the same IDE used in companies across Hyderabad, and rebuild everything Unit 1 taught — inheritance, dynamic polymorphism, an abstract class and an interface — inside it. Gently, one screen at a time.
UI24PC321CS · OOP THROUGH JAVA LAB · B.E. III SEM
Lab 2 — inheritance & polymorphism, in Eclipse.
One vehicle that starts two different ways. One content post that knows what every post must have. By the end of today both run inside an IDE that writes half your boilerplate for you.
"A program to demonstrate the concept of inheritance and dynamic Polymorphism, Abstract class & Interface."
Download, install, make a project, run a class, read the Console — and meet the debugger that shows variables changing live.
A Car overrides Vehicle's start(), and a superclass reference proves the object decides which body runs.
One abstract class and one interface meet in a single program — the exact combination the R-24 exercise (and the exam) asks for.
Nothing today is new Java. Every keyword in this lab — extends, @Override, abstract, implements — was taught across Classes 10–12. Today only the room changes: from Notepad++ and a black terminal to a workshop that watches you type. If the Java feels shaky, the drills in Part 11 warm you up before anything is graded.
ECLIPSE INSTALL · STEP 1 OF 5
Download the right Eclipse — there are many, we want one.
Eclipse ships in several flavours (for C++, for web, for testing…). We want exactly one: Eclipse IDE for Java Developers. Everything on this screen is what your own browser will show — same URL, same buttons.
Type the address yourself (typing URLs is a habit that keeps you off fake download sites). The big orange Download button auto-detects Windows 64-bit — that is the one we press.
Eclipse IDE
The open-source IDE trusted by millions of Java developers.
THE ORANGE BUTTON IS LIVE — IT OPENS THE OFFICIAL eclipse.org/downloads PAGE; PRESS ITS BIG DOWNLOAD BUTTON THERE · x86_64 = WINDOWS 64-BIT — CORRECT FOR EVERY LAB MACHINE
The button above opens the official page https://www.eclipse.org/downloads/ in a new tab — press the big Download x86_64 button there and the Eclipse Installer (~120 MB, named like eclipse-inst-jre-win64.exe) arrives from eclipse.org's own mirror. When it finishes, double-click it in your Downloads folder.
The installer lists every flavour. The one we want is first in the list. Click it once, keep the suggested install folder, then press the orange INSTALL button and accept the licence.
C:\Users\diya\eclipse\java-2026-06 — keep it
C:\Program Files\Java\jdk-21). Eclipse needs a JDK to run — you already have it.ECLIPSE INSTALL · STEP 2 OF 5
One workspace, one project — where your files will live.
Eclipse asks two "where?" questions before you can type any Java. The workspace is the folder for ALL your work this semester; the project is one named box inside it. Answer both once, correctly, and never think about them again.
On first start, Eclipse shows the Select a directory as workspace dialog. Set it to a folder you can find again, and tick the box so it never asks twice.
Close the Welcome tab (small ×), then: menu bar → File → New → Java Project. Three fields matter — and one checkbox must be UN-ticked.
module-info.java → Delete. No harm done.lab-02 with a src folder and JRE System Library [JavaSE-21] under it. That's a healthy project.ECLIPSE INSTALL · STEP 3 OF 5
Your first class, your first green-arrow run.
In Notepad++ you saved, switched to a terminal, typed javac, then java. Eclipse folds all four moves into one green arrow. Watch what it does — the same compile-then-run you already understand, just automated.
Right-click the src folder → New → Class. Name: HelloEclipse · tick public static void main(String[] args) so Eclipse types the method for you · Finish. Add one println, then press the green ▶ Run button in the toolbar.
▾ lab-02
▾ src
HelloEclipse.java
▸ JRE System Library
public class HelloEclipse{ public static void main(String[] args) { System.out.println("Hello from a real workshop!"); }}<terminated> HelloEclipse [Java Application] Hello from a real workshop!
<terminated> in its title — terminated is GOOD, it means the program ran and finished cleanly.;, a wrong case). This is the compiler talking to you WHILE you type, instead of after javac.HelloEclipse.java first, then Run.What the green arrow really did: saved the file → ran the compiler (same javac from Class 5) → launched the JVM (same java) → routed the output into the Console panel. Nothing magic was added — four of your manual steps became one button. You EARNED this button by doing it the long way for eleven classes.
ECLIPSE INSTALL · STEP 4 OF 5
The debugger — watch variables change, line by line.
The most valuable thing Eclipse adds is not speed — it's sight. The debugger pauses your program on any line and shows every variable's current value. GST on a canteen bill makes a perfect first watch.
Double-click the left margin beside line 5 — a blue dot (breakpoint) appears. Press F11 (Debug). Eclipse pauses ON that line and offers to switch to the Debug perspective — say yes. Then press F6 to execute ONE line at a time and watch the Variables view update.
bill = 240.0
gst = 12.0
total = 252.0 ← just changed
public class CanteenBill{ public static void main(String[] args) { double bill = 240.0; // ● breakpoint here — F11 pauses HERE double gst = bill * 0.05; // F6 once → gst appears = 12.0 double total = bill + gst; // F6 again → total = 252.0 System.out.println("Pay: " + total); }}CanteenBill [Java Application] — suspended at line 7 (press F8 to resume, F6 to step over)
Pay: 252.0.Why this matters for TODAY'S lab: in Exercise 1 a superclass reference will call an overridden method. If you ever doubt WHICH body ran, a breakpoint inside each start() settles it in seconds — the debugger is the fastest way to SEE dynamic dispatch choose.
ECLIPSE INSTALL · STEP 5 OF 5
Twelve shortcuts — the whole IDE under your fingers.
You don't memorise these today. You keep this card open during the exercises and let your fingers learn the four or five you actually reach for. The rest arrive on their own over the semester.
Save — and in Eclipse, save = compile. Red underlines refresh instantly.
Content Assist — suggests completions for the half-typed name under your cursor.
Format file — re-indents everything (our formatter keeps Allman braces).
Quick Fix — Eclipse proposes the repair for whatever is underlined.
Run — same as the green arrow.
Debug — run, but pause at breakpoints.
Step over — execute one line while paused.
Resume — stop stepping, run on.
Organise imports — adds/removes import lines for you.
Toggle comment — comment/uncomment the selected lines.
Rename everywhere — renames a class/variable and every use of it, safely.
Open Type — jump to any class by typing its name.
Exam-hall honesty: your written exam has no Ctrl+Space. Content Assist is a typing helper, not a thinking substitute — that's why every exercise today still begins in your ruled notebook, ink first, before Eclipse sees a single line.
ECLIPSE SESSION TOUR
One screen, six territories — learn the map once.
Everything you'll touch today lives in one of six labelled regions. The simulation below builds the workbench one territory per press — say each one's job out loud as it appears.
BUILD THE WORKBENCH — ONE TERRITORY PER PRESS
▾ lab-02
▾ src
Vehicle.java
Car.java
VehicleDriver.java
▸ JRE System Library
▾ Vehicle
● start() : void
<terminated> VehicleDriver [Java Application] Car starting with a key turn
| TERRITORY | ITS ONE JOB | YOU'LL USE IT TODAY WHEN… |
|---|---|---|
| ① Menu + toolbar | commands — New, Run ▶, Debug 🐞 | creating classes, running exercises |
| ② Package Explorer | every file in every project | right-click src → New → Class |
| ③ Editor | where you type; each tab = one file | all three Exercise-1 files sit in tabs |
| ④ Left margin | breakpoints + error markers | double-click = breakpoint; hover ⓧ = read the error |
| ⑤ Outline | this file's fields and methods | jump straight to a method in a long file |
| ⑥ Console | your program's output | every run's proof lands here |
COMFORT · CONTENT ASSIST, QUICK FIX, FORMAT
Let the IDE type the boring parts — you keep the thinking parts.
Three helpers earn their place in the first ten minutes. Try each one now on your HelloEclipse file — thirty seconds each — so they're familiar before marks are involved.
Type sysout then Ctrl+Space → it expands to the full System.out.println(); with the cursor inside the brackets. The most-used trick in Java rooms everywhere.
Click any red-underlined problem, press Ctrl+1 — Eclipse lists repairs ("add missing semicolon", "create method…"). Read the list, pick, done.
Re-indents the whole file. Our course formatter keeps Allman braces — every { and } on its own line, exactly as your notebook writes them.
The paper-exam rule stands: helpers speed up TYPING, never THINKING. In the written exam you are the content assist. Every drill below therefore starts with your pen — the IDE only gets code your notebook already holds.
PRELAB · THEORY Q1–Q3 · INK FIRST, REVEAL SECOND
One question at a time — answer, check, move on.
Everything here was taught in Classes 10–12. The rhythm is fixed: read ONE question, answer it in your ruled notebook, unlock ITS answer right below, correct your ink — only then move to the next question.
LAB
Q1
QUESTION 1 OF 5 ≤ 1 MIN
Q1. A superclass reference holds a subclass object: Vehicle v = new Car();. Which class's overridden start() runs when we call v.start() — and who decides, and when?
blue ink first — then the button below.
- The Car's overridden
start()runs — never Vehicle's. - The object decides, not the reference type.
vis only a remote pointing at whatever object it holds. - The decision happens at runtime — this is dynamic method dispatch (C10's exact phrase). The compiler only checks that some
start()exists onVehicle.
LAB
Q2
QUESTION 2 OF 5 ≤ 1 MIN
Q2. What does @Override actually DO at compile time? What kind of mistake does it catch?
answered in ink? unlock and compare.
@Overrideasks the compiler to verify that this method really overrides a superclass method — it adds zero runtime behaviour.- It catches the classic slip: a misspelled name or wrong parameter list (e.g.
strat()) that would otherwise silently become a NEW method instead of an override. - Without the annotation the code still compiles — but the bug hides. With it, the compile fails loudly on the exact line.
LAB
Q3
QUESTION 3 OF 5 ≤ 1 MIN
Q3. Can we write new ContentPost() if ContentPost is declared abstract? What CAN an abstract class give its children?
ink first — this one is Exercise 2's heart.
- No.
new ContentPost()is a compile error — an abstract class is an incomplete blueprint; Java refuses to build an object with missing method bodies. - What it CAN give its children: fields, constructors (called via
super(...)), concrete methods they inherit as-is, and abstract method signatures they must complete. - An abstract reference is still legal:
ContentPost p = new ReelPost();— the blueprint can point at any finished building.
PRELAB · THEORY Q4–Q5 · SAME RHYTHM
Two to go — question, ink, reveal.
Same discipline: answer in your notebook first, then unlock the answer sitting right under the question.
LAB
Q4
QUESTION 4 OF 5 ≤ 1 MIN
Q4. A class can extends how many classes, and implements how many interfaces? Why the difference?
the "why" is the viva half — write it too.
extends— exactly one class.implements— any number of interfaces, comma-separated.- Why the difference: two parent CLASSES could both bring a method body for the same signature — whose body wins? Java bans the ambiguity (the "diamond problem").
- Interfaces (in their classic form) bring only contracts, no bodies — signing five contracts can never clash, because YOU write every body once.
LAB
Q5
QUESTION 5 OF 5 ≤ 1 MIN
Q5. Inside an interface, what do method declarations have instead of bodies — and what must every implementing class therefore do?
last one — then the drills begin.
- Method declarations end in a semicolon instead of a body:
void share();— a promise with no work attached. - They are public and abstract by default — writing the keywords is optional, the compiler assumes them.
- Every implementing class must therefore provide a public body for every method — or declare itself
abstractand pass the debt down.
Prelab theory done. Five questions, five corrected answers in ink. Everything the graded exercises need is now warm — the coding drills next rehearse the same five ideas with your fingers instead of your pen.
PRELAB · 4 CODING DRILLS · MIRROR THE GRADED WORK 1:1
Warm fingers — each drill rehearses one graded move.
These four little programs are the graded exercises wearing simpler clothes. Drill 1–2 rehearse Exercise 1's extends + override + polymorphic call; Drill 3–4 rehearse Exercise 2's abstract class + interface. Type each in Eclipse; if a drill takes more than ten minutes, open its sheet, study it, close it, and type from memory.
A Vehicle has one field wheels (int) and a method describe() that prints it. Bike extends Vehicle and adds nothing yet.
None — set wheels = 2 in the driver before calling.
Runs on 2 wheels
Bike never declares wheels or describe() — yet has both. That's the whole meaning of extends.
class Vehicle{ int wheels; void describe() { System.out.println("Runs on " + wheels + " wheels"); }}class Bike extends Vehicle{} // empty — and yet completepublic class BikeDrill{ public static void main(String[] args) { Bike b = new Bike(); b.wheels = 2; // inherited field b.describe(); // inherited method }}extends.Vehicle.honk() prints Generic horn. Bike overrides it (with @Override) to print Tring tring!. Call it through a Vehicle reference.
None.
Tring tring! — Bike's line, despite the Vehicle-typed variable.
Vehicle v = new Bike(); then v.honk() — the object decides at runtime. Ex 1 is this exact move with start().
class Vehicle{ void honk() { System.out.println("Generic horn"); }}class Bike extends Vehicle{ @Override void honk() { System.out.println("Tring tring!"); }}public class HonkDrill{ public static void main(String[] args) { Vehicle v = new Bike(); // Vehicle remote, Bike object v.honk(); // runtime asks the OBJECT }}Vehicle; the printed line says Bike. That gap IS dynamic dispatch — set a breakpoint inside each honk() and F11 to watch the debugger land only in Bike's.abstract class Shape declares abstract double area();. Square (side 4.0) pays the debt. Print the area through a Shape reference.
Side hard-coded: 4.0.
Area: 16.0
new Shape() is a compile error; Shape s = new Square(4.0) is not. Ex 2's ContentPost is this with a constructor and a concrete method added.
abstract class Shape{ abstract double area(); // promise — no body, just ;}class Square extends Shape{ double side; Square(double side) { this.side = side; } @Override double area() { return side * side; // debt paid }}public class ShapeDrill{ public static void main(String[] args) { Shape s = new Square(4.0); // abstract reference, concrete object System.out.println("Area: " + s.area()); }}new Shape() anywhere — Eclipse underlines it instantly: "Cannot instantiate the type Shape". The IDE quotes the rule to you before javac ever would.interface Printable declares void print();. IdCard implements it and prints one line.
None.
ID: 160123733001
The body you write must be public — the interface promised the world public, and you can't honour a public promise privately.
interface Printable{ void print(); // public abstract by default}class IdCard implements Printable{ @Override public void print() // public is COMPULSORY here { System.out.println("ID: 160123733001"); }}public class PrintDrill{ public static void main(String[] args) { Printable p = new IdCard(); // interface reference works too p.print(); }}public on line 8 and save — Eclipse underlines it: "Cannot reduce the visibility of the inherited method". A promise can't shrink.LAB DAY · HOW THE NEXT TWO HOURS RUN
The walkthrough — notebook, Eclipse, run, unlock.
Both graded exercises follow the same four-station loop. Read it once now; from here on the page only says "loop" and you'll know what to do.
Read the brief. Write the class skeletons in your ruled notebook first — names, fields, method headers. Two minutes of ink saves twenty of typing.
One Eclipse class per file: right-click src → New → Class. Type your notebook code. Red underlines are the compiler helping live — hover, read, fix.
Green ▶ on the driver class. Compare the Console character by character with the expected output — marks live in that comparison.
Only after YOUR run: open the solution sheet, diff it against your code, note one thing it does better. That note is viva ammunition.
One project, all files: everything today lives in the single lab-02 Eclipse project you made in Part 3 — Exercise 1's three files AND Exercise 2's four sit together in src. No second project, no loose folders. Eclipse compiles them together automatically, exactly like javac *.java did.
GRADED · EXERCISE 1 · 45 MARKS
Exercise 1 — one Vehicle, two ways to start.
Three files, one polymorphic call. This is PYQ P2·Q11b wearing lab clothes — the exact Vehicle/Car override the exam asked, now typed, run and proven in Eclipse.
Vehicle has a field name, a constructor that sets it, and start() printing <name> starting somehow.... Car extends Vehicle, passes the name up with super(name), and overrides start() to print <name> starting with a key turn.
Create Vehicle v1 = new Vehicle("Tractor") and Vehicle v2 = new Car("Swift") — note: both references are Vehicle-typed — then call start() on each.
Tractor starting somehow...Swift starting with a key turn
Vehicle class correct — 12 · Car override + super(name) + @Override — 15 · polymorphic driver — 12 · output matches exactly — 6.
EXERCISE 1 · FULL SOLUTION · AFTER YOUR RUN ONLY
Exercise 1, solved — three files, one truth.
Unlock each file only after your own three compile. The driver's sheet also carries the run — and the PYQ chip this exercise lands.
public class Vehicle{ String name; Vehicle(String name) // ctor — Car will call this via super { this.name = name; } void start() { System.out.println(name + " starting somehow..."); }}Vehicle declares a constructor with a parameter, Java writes NO free no-arg constructor — which is exactly why Car MUST call super(name) in file 2.public class Car extends Vehicle{ Car(String name) { super(name); // hands the name up — MUST be line one } @Override void start() { System.out.println(name + " starting with a key turn"); }}extends (4) · ctor + super (5) · @Override (3) · the new body (3) = 15. Delete @Override and misspell start to see the silent-new-method trap Q2 warned about.public class VehicleDriver{ public static void main(String[] args) { Vehicle v1 = new Vehicle("Tractor"); // plain vehicle Vehicle v2 = new Car("Swift"); // Vehicle remote, Car object v1.start(); v2.start(); // the object answers, not the type }}Vehicle but Swift turns a key. That one line is dynamic polymorphism, demonstrated, graded, done.PYQ LANDING · P2·Q11b · 4 MARKS This exercise IS the exam question "Demonstrate method overriding with a Vehicle/Car example" — taught at C10, solved on paper there, now proven on a real machine. In the exam, write exactly these three classes (shrunk to one file is fine) and STATE the output; the examiner scans for extends, @Override, the superclass reference, and the correct two output lines — one mark each.
GRADED · EXERCISE 2 · 40 MARKS
Exercise 2 — a post that knows what every post must have.
One abstract class and one interface meet in a single program — the exact combination the R-24 exercise names. The domain: content posts on a creator app. Every post has a caption and must render itself; only some kinds are shareable.
abstract class ContentPost — field caption, a constructor that sets it, a concrete method showCaption() printing Caption: <caption>, and an abstract method void render();.
interface Shareable — one method: void share();. No bodies, no fields.
ReelPost extends ContentPost implements Shareable — pays BOTH debts: render() prints Playing a 30s reel, share() prints Reel shared to story.
Create ContentPost p = new ReelPost("Lab day!"), call showCaption() and render(); then Shareable s = new ReelPost("Again!") and call share().
Caption: Lab day!Playing a 30s reelReel shared to story
abstract class right — 12 · interface right — 6 · ReelPost pays both debts — 12 · driver uses BOTH reference types — 7 · output exact — 3.
Ink the four skeletons + predict all three output lines before Eclipse. The extends X implements Y header order is a favourite viva question — extends always first.
Drill 3 is ContentPost in miniature; Drill 4 is Shareable. Re-run them, then return.
EXERCISE 2 · FULL SOLUTION · AFTER YOUR RUN ONLY
Exercise 2, solved — both debts paid in one class.
Two sheets: the two contract files first, then ReelPost + driver + the real run.
public abstract class ContentPost{ String caption; ContentPost(String caption) // yes — abstract classes HAVE ctors { this.caption = caption; } void showCaption() // concrete — children inherit as-is { System.out.println("Caption: " + caption); } public abstract void render(); // the debt — no body, just ;}public interface Shareable{ void share(); // public abstract by default}public class ReelPost extends ContentPost implements Shareable{ ReelPost(String caption) { super(caption); } @Override public void render() // debt 1 — to the abstract class { System.out.println("Playing a 30s reel"); } @Override public void share() // debt 2 — to the interface { System.out.println("Reel shared to story"); }}public class PostDriver{ public static void main(String[] args) { ContentPost p = new ReelPost("Lab day!"); // abstract remote p.showCaption(); // inherited concrete method p.render(); // dispatch → ReelPost's body Shareable s = new ReelPost("Again!"); // interface remote s.share(); }}BEFORE YOU SUBMIT · FIVE CLASSIC SLIPS
Five mistakes that cost real marks today.
Each row names the slip, what Eclipse shows you, and the fix. Scan your own files against all five before calling an exercise done.
| THE SLIP | WHAT ECLIPSE SHOWS | THE FIX |
|---|---|---|
Misspelled override (strat()) without @Override | Nothing — it compiles! The generic body runs instead. | Always write @Override; then the typo becomes a loud red underline. |
Forgot super(name) in Car's constructor | "Implicit super constructor Vehicle() is undefined" | First line of the child ctor: super(name); — the parent has no free no-arg ctor. |
new ContentPost("x") — instantiating the abstract class | "Cannot instantiate the type ContentPost" | Point an abstract reference at a CONCRETE child: new ReelPost("x"). |
Interface method body not public | "Cannot reduce the visibility of the inherited method" | Interface methods are public by default — your body must say public explicitly. |
Wrote implements Vehicle / extends Shareable | "The type Vehicle cannot be a superinterface" (and mirror-image) | Classes are extended, interfaces are implemented — and extends comes first in the header. |
Row 1 is the sneakiest — it's the only one that fails SILENTLY. The other four stop your compile; row 1 ships wrong behaviour with a green run. That's why @Override costs 3 marks today: it converts the deck's most dangerous bug into its easiest.
FINISHED EARLY? · STRETCH · NOT GRADED
The insurance office — a four-class stretch.
Done and verified with time left? This stretch is PYQ P1·Q12a's scenario, full size. No marks, no sheet — just you, the ideas, and a bigger canvas.
abstract class Policy — fields holder, premium; ctor; concrete showHolder(); abstract double annualCost();
interface Renewable with void renew();
HealthPolicy (annualCost = premium × 12, renewable) and TravelPolicy (annualCost = premium × trips, NOT renewable — it simply doesn't implement).
A Policy[] loop calling annualCost() polymorphically, and renew() reachable ONLY through a Renewable reference — try it on TravelPolicy and read the compile error out loud.
Renewable r = travel refuses to compile) is the deepest lesson on this page: interfaces gate CAPABILITY, not family.DEBRIEF · WHAT TODAY ACTUALLY PROVED
Say each of these out loud — they're viva answers now.
Four sentences carry the whole lab. If any one feels shaky, its home part is one rail-dot away.
"Car wrote no name field and owns one anyway — extends hands down fields, methods and shape." (Ex 1, Drill 1)
"v2 is Vehicle-typed but Swift turned a key — the OBJECT picks the body, at runtime, every time." (Ex 1, Drill 2)
"ContentPost gave a field, a ctor and one finished method — and one debt no child may skip." (Ex 2, Drill 3)
"Shareable held zero code, yet s.share() ran — a signed contract is enough for a call." (Ex 2, Drill 4)
And one Eclipse sentence: "The green arrow is my old javac + java fused; the debugger is new sight, not new Java." Model solutions for every drill and both exercises live in this page's locked sheets — re-open any of them from the rail during revision week.
CHECKPOINT · RUBRIC /100 · WHAT TO SUBMIT
The 100 marks, line by line.
Nothing here is a surprise — every row was named beside the work it grades.
| COMPONENT | WHAT FULL MARKS LOOKS LIKE | MARKS |
|---|---|---|
| Exercise 1 — Vehicle/Car | Three files compile · super(name) + @Override present · both output lines exact through Vehicle-typed references | 45 |
| Exercise 2 — ContentPost/Shareable | Abstract class + interface both correct · ReelPost pays both debts publicly · driver uses both reference types · three lines exact | 40 |
| Style | Allman braces everywhere (Ctrl+Shift+F keeps them) · honest names · no dead code | 5 |
| Viva — two questions | One dispatch question (expect "who picks the body?") · one abstract-vs-interface question — Part 19's sentences ARE the answers | 10 |
- Ruled notebook — prelab Q1–Q5 answered in ink, both exercises' skeletons + output predictions.
- Eclipse project
lab-02shown running on your machine — the examiner presses ▶ on both drivers and reads your Console. - One sentence out loud when asked: what did
Vehicle v2 = new Car("Swift")prove?