Unit 1 home
LAB 2 · FIRST ECLIPSE LAB UI24PC321CS AFTER CLASS 12
LAB 2SPACE / → = NEXT · ← = BACK
01

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.

R-24 SYLLABUS · LAB EXERCISE 2 · VERBATIM

"A program to demonstrate the concept of inheritance and dynamic Polymorphism, Abstract class & Interface."

NEW TOOLEclipse IDE for Java Developers
GRADED WORK2 exercises · 100 marks total
YOU ALREADY KNOWextends · @Override · abstract · implements (C10–C12)
EXAM LINKExercise 1 IS PYQ P2·Q11b in lab clothes
Eclipse IDE logo — deep indigo sphere with orange crescent
Objective 1 — install & run Eclipse

Download, install, make a project, run a class, read the Console — and meet the debugger that shows variables changing live.

Objective 2 — override polymorphically

A Car overrides Vehicle's start(), and a superclass reference proves the object decides which body runs.

Objective 3 — abstract + interface together

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.

02

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.

1Open the official download page — and only the official oneWINDOWS 11 · CHROME

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.

https://www.eclipse.org/downloads/
Eclipse IDE logo on the download page

Eclipse IDE

The open-source IDE trusted by millions of Java developers.

Download x86_64 Other packages…

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.

2In the installer, pick "Eclipse IDE for Java Developers"ECLIPSE INSTALLER WINDOW · WINDOWS 11

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.

eclipseinstaller
Eclipse IDE for Java Developers  ✓ SELECTED
Eclipse IDE for Enterprise Java · for C/C++ · for Web · for Testers…
INSTALL installation folder: C:\Users\diya\eclipse\java-2026-06 — keep it
VERIFY: when the installer finishes, a green LAUNCH button appears. Press it once — if an Eclipse splash screen with the indigo sphere appears, the install worked. Close it again; we set the workspace properly in Step 3.
"Windows protected your PC" blue box?Click More info → Run anyway — the download is official; you typed the URL yourself.
Installer asks for a JDK?Point it at the JDK 21 you installed in Class 5 (C:\Program Files\Java\jdk-21). Eclipse needs a JDK to run — you already have it.
03

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.

3First launch — set the workspaceWORKSPACE LAUNCHER · WINDOWS 11

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.

Eclipse IDE Launcher
C:\Users\diya\eclipse-workspace
Use this as the default and do not ask again
LaunchCancel
4File → New → Java ProjectNEW JAVA PROJECT WIZARD · WINDOWS 11

Close the Welcome tab (small ×), then: menu bar → File → New → Java Project. Three fields matter — and one checkbox must be UN-ticked.

New Java Project
FileEditSourceRefactorNavigateSearchProjectRunWindowHelp
lab-02
JavaSE-21  ▾
Create module-info.java file  ← UN-TICK THIS
FinishCancel
Why un-tick module-info? Modules are a large-project feature from a much later world. In lab work the file only confuses. If you forgot and it appeared: right-click module-info.java → Delete. No harm done.
VERIFY: the Package Explorer on the left now shows lab-02 with a src folder and JRE System Library [JavaSE-21] under it. That's a healthy project.
04

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.

5New → Class, then RunECLIPSE WORKBENCH · WINDOWS 11

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.

eclipse-workspace — lab-02/src/HelloEclipse.java — Eclipse IDE
FileEditSourceRefactorNavigateSearchProjectRun ▶WindowHelp
PACKAGE EXPLORER
▾ lab-02
  ▾ src
    HelloEclipse.java
  ▸ JRE System Library
HelloEclipse.java — EXACTLY WHAT YOU TYPE
1public class HelloEclipse
2{
3 public static void main(String[] args)
4 {
5 System.out.println("Hello from a real workshop!");
6 }
7}
Console ×   Problems  Javadoc
<terminated> HelloEclipse [Java Application]
Hello from a real workshop!
VERIFY: the Console panel at the bottom prints your line with <terminated> in its title — terminated is GOOD, it means the program ran and finished cleanly.
Red underline under your code?Hover it — Eclipse names the exact problem (a missing ;, a wrong case). This is the compiler talking to you WHILE you type, instead of after javac.
"Selection does not contain a main type"?You pressed Run with the wrong file selected. Click inside 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.

05

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.

6Breakpoint → F11 → F6, F6, F6DEBUG PERSPECTIVE · WINDOWS 11

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.

Debug — lab-02/src/CanteenBill.java — Eclipse IDE
VARIABLES VIEW · AFTER 3 × F6
bill   = 240.0
gst    = 12.0
total = 252.0 ← just changed
CanteenBill.java — PAUSED, NOT CRASHED
1public class CanteenBill
2{
3 public static void main(String[] args)
4 {
5 double bill = 240.0; // ● breakpoint here — F11 pauses HERE
6 double gst = bill * 0.05; // F6 once → gst appears = 12.0
7 double total = bill + gst; // F6 again → total = 252.0
8 System.out.println("Pay: " + total);
9 }
10}
Console ×   Breakpoints  Expressions
CanteenBill [Java Application] — suspended at line 7
(press F8 to resume, F6 to step over)
The three keys that matter: F11 = start debugging · F6 = run ONE line, stay in this method · F8 = stop stepping, run to the end (or the next breakpoint). That's the whole starter kit — F5 (step INTO a method) joins later when your methods call methods.
VERIFY: after two presses of F6 the Variables view shows all three values (240.0 / 12.0 / 252.0) — you just watched arithmetic happen one line at a time. Press F8 to let it finish; the Console prints 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.

06

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.

Ctrl + S

Save — and in Eclipse, save = compile. Red underlines refresh instantly.

Ctrl + Space

Content Assist — suggests completions for the half-typed name under your cursor.

Ctrl + Shift + F

Format file — re-indents everything (our formatter keeps Allman braces).

Ctrl + 1

Quick Fix — Eclipse proposes the repair for whatever is underlined.

Ctrl + F11

Run — same as the green arrow.

F11

Debug — run, but pause at breakpoints.

F6

Step over — execute one line while paused.

F8

Resume — stop stepping, run on.

Ctrl + Shift + O

Organise imports — adds/removes import lines for you.

Ctrl + /

Toggle comment — comment/uncomment the selected lines.

Alt + Shift + R

Rename everywhere — renames a class/variable and every use of it, safely.

Ctrl + Shift + T

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.

07

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

eclipse-workspace — lab-02 — Eclipse IDE
① MENU + TOOLBARFileEditSourceRun ▶ 🐞WindowHelp
② PACKAGE EXPLORER — your files
▾ lab-02
  ▾ src
    Vehicle.java
    Car.java
    VehicleDriver.java
  ▸ JRE System Library
⑤ OUTLINE — this file's members
▾ Vehicle
  ● start() : void
Vehicle.java ×  |  Car.java  |  VehicleDriver.java
● blue dot = breakpoint · ⓧ red circle = compile error on that line
⑥ CONSOLE ×   Problems  Javadoc  Declaration
<terminated> VehicleDriver [Java Application]
Car starting with a key turn
TERRITORYITS ONE JOBYOU'LL USE IT TODAY WHEN…
① Menu + toolbarcommands — New, Run ▶, Debug 🐞creating classes, running exercises
② Package Explorerevery file in every projectright-click src → New → Class
③ Editorwhere you type; each tab = one fileall three Exercise-1 files sit in tabs
④ Left marginbreakpoints + error markersdouble-click = breakpoint; hover ⓧ = read the error
⑤ Outlinethis file's fields and methodsjump straight to a method in a long file
⑥ Consoleyour program's outputevery run's proof lands here
08

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.

Content Assist · Ctrl+Space

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.

Quick Fix · Ctrl+1

Click any red-underlined problem, press Ctrl+1 — Eclipse lists repairs ("add missing semicolon", "create method…"). Read the list, pick, done.

Format · Ctrl+Shift+F

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.

09

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.

PRE
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.

Q1 — who picks the start() that runs?
MODEL ANSWER · Q1
  • The Car's overridden start() runs — never Vehicle's.
  • The object decides, not the reference type. v is 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 on Vehicle.
PRE
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.

Q2 — what does @Override do?
MODEL ANSWER · Q2
  • @Override asks 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.
PRE
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.

Q3 — can we new an abstract class?
MODEL ANSWER · Q3
  • 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.
10

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.

PRE
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.

Q4 — how many extends, how many implements?
MODEL ANSWER · Q4
  • extendsexactly one class. implementsany 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.
PRE
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.

Q5 — what lives inside an interface?
MODEL ANSWER · Q5
  • 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 abstract and 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.

11

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.

DRILL 1Bike extends Vehicle — plain inheritanceMIRRORS EX 1 · NOT GRADED
PROBLEM

A Vehicle has one field wheels (int) and a method describe() that prints it. Bike extends Vehicle and adds nothing yet.

INPUT

None — set wheels = 2 in the driver before calling.

EXPECTED OUTPUT

Runs on 2 wheels

THE ONE IDEA

Bike never declares wheels or describe() — yet has both. That's the whole meaning of extends.

only after your attempt — stuck 10 min is the ticket in
DRILL 1 · SOLVED — ONE FILE, THREE CLASSES (FINE FOR A DRILL)
BikeDrill.java
1class Vehicle
2{
3 int wheels;
4 void describe()
5 {
6 System.out.println("Runs on " + wheels + " wheels");
7 }
8}
9class Bike extends Vehicle
10{
11} // empty — and yet complete
12public class BikeDrill
13{
14 public static void main(String[] args)
15 {
16 Bike b = new Bike();
17 b.wheels = 2; // inherited field
18 b.describe(); // inherited method
19 }
20}
ECLIPSE CONSOLE
<terminated> BikeDrill [Java Application]
Runs on 2 wheels
Line 11's empty braces are the proof: Bike wrote nothing and owns everything — both the field and the method arrived through extends.
DRILL 2Bike.honk() override + a Vehicle referenceMIRRORS EX 1 · NOT GRADED
PROBLEM

Vehicle.honk() prints Generic horn. Bike overrides it (with @Override) to print Tring tring!. Call it through a Vehicle reference.

INPUT

None.

EXPECTED OUTPUT

Tring tring! — Bike's line, despite the Vehicle-typed variable.

THE ONE IDEA

Vehicle v = new Bike(); then v.honk() — the object decides at runtime. Ex 1 is this exact move with start().

notebook first, always
DRILL 2 · SOLVED — THE POLYMORPHIC CALL
HonkDrill.java
1class Vehicle
2{
3 void honk()
4 {
5 System.out.println("Generic horn");
6 }
7}
8class Bike extends Vehicle
9{
10 @Override
11 void honk()
12 {
13 System.out.println("Tring tring!");
14 }
15}
16public class HonkDrill
17{
18 public static void main(String[] args)
19 {
20 Vehicle v = new Bike(); // Vehicle remote, Bike object
21 v.honk(); // runtime asks the OBJECT
22 }
23}
ECLIPSE CONSOLE
<terminated> HonkDrill [Java Application]
Tring tring!
The variable's type says 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.
DRILL 3abstract Shape — one debt, one payerMIRRORS EX 2 · NOT GRADED
PROBLEM

abstract class Shape declares abstract double area();. Square (side 4.0) pays the debt. Print the area through a Shape reference.

INPUT

Side hard-coded: 4.0.

EXPECTED OUTPUT

Area: 16.0

THE ONE IDEA

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.

attempt first — the error message for new Shape() is worth seeing live
DRILL 3 · SOLVED — THE INCOMPLETE BLUEPRINT
ShapeDrill.java
1abstract class Shape
2{
3 abstract double area(); // promise — no body, just ;
4}
5class Square extends Shape
6{
7 double side;
8 Square(double side)
9 {
10 this.side = side;
11 }
12 @Override
13 double area()
14 {
15 return side * side; // debt paid
16 }
17}
18public class ShapeDrill
19{
20 public static void main(String[] args)
21 {
22 Shape s = new Square(4.0); // abstract reference, concrete object
23 System.out.println("Area: " + s.area());
24 }
25}
ECLIPSE CONSOLE
<terminated> ShapeDrill [Java Application]
Area: 16.0
Try typing new Shape() anywhere — Eclipse underlines it instantly: "Cannot instantiate the type Shape". The IDE quotes the rule to you before javac ever would.
DRILL 4Printable interface — sign it, honour itMIRRORS EX 2 · NOT GRADED
PROBLEM

interface Printable declares void print();. IdCard implements it and prints one line.

INPUT

None.

EXPECTED OUTPUT

ID: 160123733001

THE ONE IDEA

The body you write must be public — the interface promised the world public, and you can't honour a public promise privately.

last drill — Ex 2's Shareable is this same shape
DRILL 4 · SOLVED — CONTRACT SIGNED AND HONOURED
PrintDrill.java
1interface Printable
2{
3 void print(); // public abstract by default
4}
5class IdCard implements Printable
6{
7 @Override
8 public void print() // public is COMPULSORY here
9 {
10 System.out.println("ID: 160123733001");
11 }
12}
13public class PrintDrill
14{
15 public static void main(String[] args)
16 {
17 Printable p = new IdCard(); // interface reference works too
18 p.print();
19 }
20}
ECLIPSE CONSOLE
<terminated> PrintDrill [Java Application]
ID: 160123733001
Delete the word public on line 8 and save — Eclipse underlines it: "Cannot reduce the visibility of the inherited method". A promise can't shrink.
12

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.

Station 1 — ink

Read the brief. Write the class skeletons in your ruled notebook first — names, fields, method headers. Two minutes of ink saves twenty of typing.

Station 2 — type

One Eclipse class per file: right-click src → New → Class. Type your notebook code. Red underlines are the compiler helping live — hover, read, fix.

Station 3 — run

Green ▶ on the driver class. Compare the Console character by character with the expected output — marks live in that comparison.

Station 4 — unlock

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.

13

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.

EXERCISE 1Vehicle.java · Car.java · VehicleDriver.java45 MARKS
PROBLEM

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.

THE DRIVER MUST

Create Vehicle v1 = new Vehicle("Tractor") and Vehicle v2 = new Car("Swift") — note: both references are Vehicle-typed — then call start() on each.

EXPECTED OUTPUT

Tractor starting somehow...
Swift starting with a key turn

MARKS MAP

Vehicle class correct — 12 · Car override + super(name) + @Override15 · polymorphic driver — 12 · output matches exactly — 6.

Notebook prediction before you run: write BOTH output lines in ink, then run. If line 2 surprises you, re-read Drill 2 — same physics.
14

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.

File 1 of 3 — Vehicle.java, the superclass
EXERCISE 1 · FILE 1/3 — Vehicle.java
src/Vehicle.java
1public class Vehicle
2{
3 String name;
4 Vehicle(String name) // ctor — Car will call this via super
5 {
6 this.name = name;
7 }
8 void start()
9 {
10 System.out.println(name + " starting somehow...");
11 }
12}
WHAT THIS FILE CONTRIBUTES
field: name — every Vehicle has one
ctor: sets it — no default ctor survives
start(): the GENERIC voice — "somehow..."
Because 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.
File 2 of 3 — Car.java, the override
EXERCISE 1 · FILE 2/3 — Car.java
src/Car.java
1public class Car extends Vehicle
2{
3 Car(String name)
4 {
5 super(name); // hands the name up — MUST be line one
6 }
7 @Override
8 void start()
9 {
10 System.out.println(name + " starting with a key turn");
11 }
12}
WHAT THIS FILE CONTRIBUTES
extends: Car IS-A Vehicle
super(name): parent's ctor runs first
start() REPLACED — same signature, new body
The four hot lines ARE the marks: 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.
File 3 of 3 — VehicleDriver.java + the real Console run
EXERCISE 1 · FILE 3/3 — VehicleDriver.java + RUN
src/VehicleDriver.java
1public class VehicleDriver
2{
3 public static void main(String[] args)
4 {
5 Vehicle v1 = new Vehicle("Tractor"); // plain vehicle
6 Vehicle v2 = new Car("Swift"); // Vehicle remote, Car object
7 v1.start();
8 v2.start(); // the object answers, not the type
9 }
10}
ECLIPSE CONSOLE — THE REAL RUN
<terminated> VehicleDriver [Java Application]
Tractor starting somehow...
Swift starting with a key turn
Two identical-looking calls, two different bodies — line 8's variable says 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.

15

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.

EXERCISE 2ContentPost.java · Shareable.java · ReelPost.java · PostDriver.java40 MARKS
THE ABSTRACT CLASS

abstract class ContentPost — field caption, a constructor that sets it, a concrete method showCaption() printing Caption: <caption>, and an abstract method void render();.

THE INTERFACE

interface Shareable — one method: void share();. No bodies, no fields.

THE CONCRETE CLASS

ReelPost extends ContentPost implements Shareable — pays BOTH debts: render() prints Playing a 30s reel, share() prints Reel shared to story.

THE DRIVER MUST

Create ContentPost p = new ReelPost("Lab day!"), call showCaption() and render(); then Shareable s = new ReelPost("Again!") and call share().

EXPECTED OUTPUT

Caption: Lab day!
Playing a 30s reel
Reel shared to story

MARKS MAP

abstract class right — 12 · interface right — 6 · ReelPost pays both debts — 12 · driver uses BOTH reference types — 7 · output exact — 3.

NOTEBOOK FIRST

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.

STUCK?

Drill 3 is ContentPost in miniature; Drill 4 is Shareable. Re-run them, then return.

16

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.

Files 1–2 of 4 — the abstract class + the interface
EXERCISE 2 · FILES 1–2/4 — ContentPost.java + Shareable.java
src/ContentPost.java
1public abstract class ContentPost
2{
3 String caption;
4 ContentPost(String caption) // yes — abstract classes HAVE ctors
5 {
6 this.caption = caption;
7 }
8 void showCaption() // concrete — children inherit as-is
9 {
10 System.out.println("Caption: " + caption);
11 }
12 public abstract void render(); // the debt — no body, just ;
13}
src/Shareable.java
1public interface Shareable
2{
3 void share(); // public abstract by default
4}
Read the difference out loud: the abstract class carries a field, a constructor and a finished method — it's a half-built house. The interface carries nothing but a promise — it's only a signboard. Ex 2 exists to make you FEEL that difference in your fingers.
Files 3–4 of 4 — ReelPost + PostDriver + the real Console run
EXERCISE 2 · FILES 3–4/4 — ReelPost.java + PostDriver.java + RUN
src/ReelPost.java
1public class ReelPost extends ContentPost implements Shareable
2{
3 ReelPost(String caption)
4 {
5 super(caption);
6 }
7 @Override
8 public void render() // debt 1 — to the abstract class
9 {
10 System.out.println("Playing a 30s reel");
11 }
12 @Override
13 public void share() // debt 2 — to the interface
14 {
15 System.out.println("Reel shared to story");
16 }
17}
src/PostDriver.java
1public class PostDriver
2{
3 public static void main(String[] args)
4 {
5 ContentPost p = new ReelPost("Lab day!"); // abstract remote
6 p.showCaption(); // inherited concrete method
7 p.render(); // dispatch → ReelPost's body
8 Shareable s = new ReelPost("Again!"); // interface remote
9 s.share();
10 }
11}
ECLIPSE CONSOLE — THE REAL RUN
<terminated> PostDriver [Java Application]
Caption: Lab day!
Playing a 30s reel
Reel shared to story
One object answered three different callers: the inherited concrete method, the abstract-class remote, and the interface remote. That's the whole R-24 sentence — inheritance, dynamic polymorphism, abstract class AND interface — running in eleven lines of driver.
17

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 SLIPWHAT ECLIPSE SHOWSTHE FIX
Misspelled override (strat()) without @OverrideNothing — 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.

18

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.

STRETCHInsurance policies — abstract + interface at real size0 MARKS · PURE MUSCLE
BUILD

abstract class Policy — fields holder, premium; ctor; concrete showHolder(); abstract double annualCost();

PLUS

interface Renewable with void renew();

TWO CHILDREN

HealthPolicy (annualCost = premium × 12, renewable) and TravelPolicy (annualCost = premium × trips, NOT renewable — it simply doesn't implement).

DRIVER PROVES

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.

Why it's worth it: two siblings with DIFFERENT formulas under one abstract remote is the exam's favourite escalation of today's exercise — and the last error you hit (Renewable r = travel refuses to compile) is the deepest lesson on this page: interfaces gate CAPABILITY, not family.
19

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.

Inheritance

"Car wrote no name field and owns one anyway — extends hands down fields, methods and shape." (Ex 1, Drill 1)

Dynamic polymorphism

"v2 is Vehicle-typed but Swift turned a key — the OBJECT picks the body, at runtime, every time." (Ex 1, Drill 2)

Abstract class

"ContentPost gave a field, a ctor and one finished method — and one debt no child may skip." (Ex 2, Drill 3)

Interface

"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.

20

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.

COMPONENTWHAT FULL MARKS LOOKS LIKEMARKS
Exercise 1 — Vehicle/CarThree files compile · super(name) + @Override present · both output lines exact through Vehicle-typed references45
Exercise 2 — ContentPost/ShareableAbstract class + interface both correct · ReelPost pays both debts publicly · driver uses both reference types · three lines exact40
StyleAllman braces everywhere (Ctrl+Shift+F keeps them) · honest names · no dead code5
Viva — two questionsOne dispatch question (expect "who picks the body?") · one abstract-vs-interface question — Part 19's sentences ARE the answers10
WHAT TO SUBMIT before you leaveLAB 2 · CHECKPOINT
  • Ruled notebook — prelab Q1–Q5 answered in ink, both exercises' skeletons + output predictions.
  • Eclipse project lab-02 shown 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?
DONE MEANS: both drivers run clean · all five mistake-rows checked · notebook signed. Eclipse stays installed — every lab from here on lives in it.