Unit 1 home
CLASS 8 · PART C YOUR FIRST REAL JAVA CLASS UNIT I · UI24PC320CS
CLASS 8 · P 1/13PGDN NEXT POINT · PGUP BACK

UI24PC320CS · OOP THROUGH JAVA · UNIT I · PART C · CRIMSON

Your first real Java class —
methods first, constructors second, this last.

Seven classes of story, pictures and machinery. Today the sealed box from Class 2 finally becomes code you write: a class with fields, methods that do arithmetic, constructors that build objects — and the one keyword that saves you when names collide.

C6 · JVM ARCHITECTURE C7 · EXECUTION ENGINE C8 · YOUR FIRST REAL CLASS LAB 1 · BOOK + OVERLOADING
THE HOOKThe blueprint from Class 2, finally typed — fields, methods, new, this
TODAY'S SPANwrite a class · new · method anatomy · signatures · overloading · constructors · this
ACTIVITY1 locked debugging activity — the missing-this bug every batch writes once
FEEDSLab 1 directly — Book, two constructors, two overloaded methods

Carry one question through this hour: when you write greet("Diya") and greet("Diya", 3) and BOTH work — same name, different behaviour — how does the compiler know which one you meant? The answer is one rule, it has a name, and Lab 1 will make you use it six times.

CLASS 8 · THE ROAD FOR TODAY

Today you stop reading Java and start writing it.

Every program so far had one class with one main. Today you write a class that models a THING — with its own facts and its own operations — and a second class that uses it. This is the exact skill Lab 1 examines.

BY THE END OF TODAY YOU CAN

  • writea class with fields + methods, create objects with new, and call their methods from main
  • debugthe missing-this bug — every field printing null — in under two minutes
  • classifywhich overloaded method (or constructor) the compiler picks for any call — by signature, never by return type
  • designa small class on paper — fields, two constructors, one method — the Lab-1 warm-up move

WHERE THIS SITS

SEQUENCE NOTE · v7.15 AUDIT B1 Until v7.14 this class taught constructors BEFORE methods. That was backwards: a constructor is a method that carries the class's name, and constructor overloading is method-overload resolution applied to it. Method anatomy now comes first — so when constructors arrive, they are one new rule, not three.

TODAY'S ROAD · 13 PARTS

  • Writing a class — fields + methods in one unitCODE
  • Creating objects with newCODE
  • Method anatomy — the 5 labelled piecesEXAM CORE
  • Signatures — how the compiler tells methods apartRULE
  • Method overloading + resolution drillDRILL
  • Worked example — GameScore, with live mathsMATHS
  • Constructors — a method with the class's nameCODE
  • Constructor overloading — the same rule againRULE
  • this + this() chainingKEYWORD
  • Debugging activity — everyone's name is nullNOTEBOOK

CLASS 08 OF 60 · 14 PAGES · FEEDS LAB 1

PART 3 · THE SEALED BOX, TYPED

A class is facts + operations, in one named unit.

Class 2's register drawing, line by line. A field is a fact every object of this class carries. A method is an operation that works on those facts. Watch a Student class assemble — no main here, this file is pure blueprint.

MINI PROBLEM · STUDENT.JAVA
PROBLEM
Write your first pure blueprint: a Student class holding facts and one operation — no main, on purpose. Save as Student.java in java-practice\class-08\.
REQUIRE­MENTS
  • Two fields: String name and int marks.
  • One method void printCard() that prints name + " scored " + marks — reading the fields directly, without being handed them.
  • Allman braces — every { on its own line; no main anywhere in this file.
EXPECTED OUTPUT
javac is silent (Student.class is born); java Student refuses: Main method not found. A blueprint describes — it doesn't start.
Student.java — THE BLUEPRINT
1public class Student
2{
3 String name; // field 1 — a fact every student has
4 int marks; // field 2 — another fact
5
6 void printCard() // method — an operation ON those facts
7 {
8 System.out.println(name + " scored " + marks);
9 }
10}
COMPILES — BUT REFUSES TO RUN

C:\Users\diya\Desktop\java-practice\class-08> javac Student.java

C:\Users\diya\Desktop\java-practice\class-08> java Student

Error: Main method not found in class Student, please define the main method as:

public static void main(String[] args)

javac's silence = Student.class was born. The refusal comes only from java: a blueprint describes, it doesn't start. The driver file in Part 4 provides the main door.

Allman braces, always. Every { on its own line — the house style of this course, and the style your lab evaluations expect.
No main in this file — on purpose. A blueprint doesn't run; it describes. Ten lines: two facts, one operation, sealed in one named unit. This is the flat register's shape, in Java.
Note what printCard can see. It uses name and marks WITHOUT being handed them — methods of the class see the fields of the class. Facts and operations, together.
Compile it anyway.

javac Student.java happily produces Student.class — a blueprint compiles fine without a main. It only refuses to run: java Student answers "Main method not found". Blueprints describe; they don't start.

STILL PART 3 · NAME THE FAMILIES · JAVA'S THREE KINDS OF VARIABLES

You now own two of Java's three variable families. Name all three today.

Class 3's boxes lived inside main and died at its } — those are local variables. Today's name and marks live inside the CLASS but outside every method — those are instance variables (the formal name for fields). The third family, static variables, arrives next class — one slot on the class itself, shared by every object.

LOCAL VARIABLEINSTANCE VARIABLE (field)STATIC VARIABLE (next class)
Declaredinside a method / blockinside the class, outside every methodinside the class, with static
One copy per…method CALL — fresh boxes every callOBJECT — every new Student() gets its own name + marksCLASS — exactly one, no matter how many objects
Default valueNONE — read before filling = compile errorauto: 0 / 0.0 / false / nullauto: same mercy as fields
Born / diesat its declaration / at the block's }with the object (new) / when the object is collectedat class load / when the program ends
Example todayint bill inside main (Class 3)String name · int marks (line 3–4 above)college — every student, one college (Class 9)

The flat picture, one sentence each: a local variable is a chit in your pocket — gone when the errand ends. An instance variable is a page in ONE flat's register — each flat's register has its own. A static variable is the notice on the building's board — one board, every flat reads the same notice. Keep the three pictures; Class 9's memory map hangs everything on them.

Why the default-value row is the exam row: the same 2-mark question hides in every paper — "an uninitialised field prints 0/null (defaults are for fields), but an uninitialised local variable will not even compile." You proved the local half in Class 3's TwoWorlds drill; line 3 above is the field half — new Student() with nothing set prints null scored 0.

PART 4 · FROM BLUEPRINT TO BUILDING

new — the stamp that makes an object.

Class 2 said it in pictures: the blueprint is drawn once, objects are stamped many times. new IS that stamp. A second file drives the blueprint — two students, two separate sets of facts, one shared method definition.

MINI PROBLEM · CAMPUSDRIVER.JAVA
PROBLEM
Drive the blueprint: stamp two Student objects with new and prove each carries its own facts. Save as CampusDriver.java beside Student.java.
REQUIRE­MENTS
  • A main method — this file is the door the JVM enters.
  • Student s1 = new Student(); — set name "Diya", marks 91; then s2 — "Rohit", 84.
  • Call printCard() on both; compile both files together: javac Student.java CampusDriver.java.
EXPECTED OUTPUT
Diya scored 91 then Rohit scored 84 — one shared printCard definition, two private sets of facts.
CampusDriver.java — USES THE BLUEPRINT
1public class CampusDriver
2{
3 public static void main(String[] args)
4 {
5 Student s1 = new Student(); // stamp #1
6 s1.name = "Diya";
7 s1.marks = 91;
8 Student s2 = new Student(); // stamp #2 — fresh facts
9 s2.name = "Rohit";
10 s2.marks = 84;
11 s1.printCard();
12 s2.printCard();
13 }
14}
FULL RUN

C:\Users\diya\Desktop\java-practice\class-08> javac Student.java CampusDriver.java

C:\Users\diya\Desktop\java-practice\class-08> java CampusDriver

Diya scored 91

Rohit scored 84

Same ONE printCard definition — but s1's call reads s1's facts, s2's call reads s2's. Each object carries its own copy of the fields; the method is shared machinery.

Where does each piece live? You already know. Class 6's floor plan: the blueprint (Student.class) sits ONCE on the Method Area shelf; every new allocates a fresh object in the Heap; s1, s2 are references on main's Stack frame.

THE BLUEPRINT ECONOMY, NOW IN BYTES — CLASS-2'S TABLE, MEASURED

WHATHOW MANYARITHMETICMEMORY
printCard's code (Method Area)1 — always 1≈ 60 bytes × 1≈ 60 B
Student objects, our driver (Heap)2≈ 24 B × 2≈ 48 B
Student objects, college ERP (Heap)28,000≈ 24 B × 28,000≈ 672 KB — and STILL one 60-byte printCard

28,000 objects, ONE method definition. If each object carried its own copy of the code: 60 B × 28,000 ≈ 1.7 MB wasted on duplicates. The class/object split isn't philosophy — it's arithmetic.

PART 5 · THE 5 PIECES · EXAM CORE

Anatomy of a method — five pieces, every time.

Everything left in this class — signatures, overloading, constructors, this — builds on naming these five pieces cold. One press lights one piece; say its name before its card appears.

ONE PRESS = ONE PIECE, LEFT TO RIGHT

1public 2int 3add 4(int a, int b) 5{ return a + b; }
1
MODIFIER · public

Who may call it. For now: public = anyone. The full menu (private, protected) arrives in Class 13.

2
RETURN TYPE · int

What comes BACK. void = nothing comes back (printCard). Here: one int.

3
NAME · add

A verb, lowerCamelCase. Half of the method's identity — the other half is piece 4.

4
PARAMETER LIST · (int a, int b)

What must be handed IN — types, order, count. Pieces 3 + 4 together form the signature: the method's fingerprint. Next part is entirely about this.

5
BODY · { return a + b; }

What it actually does. The only piece the caller never sees — abstraction, from Class 2's pillars.

Now re-read a line you've typed for seven classes: public static void main(String[] args) — modifier(s), return type, name, parameter list. It was method anatomy all along.

PART 6 · THE FINGERPRINT

The signature — what makes
one method THIS method.

The compiler never identifies a method by name alone. It uses the signature — and knowing exactly what is IN it (and what is NOT) is the difference between predicting the compiler and being surprised by it.

IN the signature

The method's name + the parameter list: the TYPES of the parameters, their ORDER, and their COUNT. add(int, int) — that whole shape is the fingerprint.

NOT in the signature

The return type · the parameter NAMES (add(int a, int b) and add(int x, int y) are the SAME method) · the modifier (public/private changes visibility, not identity).

Why the return type can't count

At the call site obj.add(2, 3); the caller may IGNORE the result — so the compiler often can't see any return type to choose by. Only the argument shape is always visible. That's the design reason, not a rule to memorise.

The 2-mark trap, verbatim: "Can two methods differ ONLY in return type?"

No. int get() and double get() in one class have the SAME signature get() — the compiler rejects the second as a duplicate. Answer with the reason from the third card and you've turned 2 marks into a certainty.

Say it like a phone contact: a person's identity in your phone is name + number — not their ringtone. A method's identity is name + parameter shape — not its return type. Change the ringtone, same contact. Change the return type, same method — and that's exactly why Java refuses the duplicate.

PART 7 · ONE NAME, MANY SHAPES

Overloading — same name,
different fingerprints.

If signatures are fingerprints, then one class can hold several methods with the SAME NAME — as long as every fingerprint differs. That is method overloading, and it is the exact skill Lab 1 will grade.

MINI PROBLEM · GREETER.JAVA
PROBLEM
Put three methods with the SAME name in one class — legally — by giving each a different fingerprint. Save as Greeter.java in java-practice\class-08\.
REQUIRE­MENTS
  • void greet() — prints Hello, class!
  • void greet(String name) — prints Hello, name!
  • void greet(String name, int times) — loops times times, each pass delegating to greet(name) — never repeating the println.
EXPECTED OUTPUT
javac silent — three fingerprints coexist. In JShell, g.greet("Diya", 3) prints Hello, Diya! three times.
Greeter.java — THREE greet(), THREE FINGERPRINTS
1public class Greeter
2{
3 void greet() // fingerprint: greet()
4 { System.out.println("Hello, class!"); }
5
6 void greet(String name) // fingerprint: greet(String)
7 { System.out.println("Hello, " + name + "!"); }
8
9 void greet(String name, int times) // fingerprint: greet(String,int)
10 {
11 for (int i = 0; i < times; i++)
12 {
13 greet(name); // one overload CALLING another — legal & smart
14 }
15 }
16}
COMPILE, THEN POKE IT IN JSHELL

C:\Users\diya\Desktop\java-practice\class-08> javac Greeter.java

C:\Users\diya\Desktop\java-practice\class-08> jshell

jshell> /open Greeter.java

jshell> Greeter g = new Greeter()

g ==> Greeter@2f4d3709

jshell> g.greet("Diya", 3)

Hello, Diya!

Hello, Diya!

Hello, Diya!

javac first — silence means the three fingerprints coexist legally. Then JShell: the (String,int) overload loops three times, each pass DELEGATING to greet(String). No driver file needed to prove a blueprint works.

Same name × 3 — and javac is happy. Because the three parameter shapes differ: (), (String), (String,int). Three distinct fingerprints from Part 6, peacefully in one class.
Line 13 is the professional move. The 2-parameter overload doesn't repeat the println — it delegates to the 1-parameter one. One place to fix the greeting text later. Remember Class 2's cohesion: each method does ONE job.
Why overload at all? The caller thinks "greet" and the compiler picks the right shape — instead of you inventing greetNoArgs, greetWithName, greetNameTimes. You already USE this daily: println(), println(int), println(String) are overloads.

RESOLUTION DRILL · PREDICT IN YOUR NOTEBOOK, THEN PRESS — ONE VERDICT PER PRESS

g.greet();
Zero arguments — the only zero-parameter fingerprint.
greet() ✓
g.greet("Diya");
One String — exactly one fingerprint takes a lone String.
greet(String) ✓
g.greet("Diya", 3);
String then int, in that order — the 2-parameter fingerprint.
greet(String,int) ✓
g.greet(3, "Diya");
int then String — ORDER is part of the fingerprint, and no overload has this order.
COMPILE ERROR ✗
g.greet('D');
'D' is a char — not a String. char widens to int, but NO overload takes one int/char either. The compiler will not invent a conversion to String.
COMPILE ERROR ✗

Score yourself honestly: 5/5 means you already think like javac. The two errors are the marks-earners — order matters, and char ≠ String.

Definition line for the exam — memorise it exactly.

Method overloading: defining two or more methods in the same class with the same name but different parameter lists (different types, order, or count). Resolved by the compiler at compile time — which is why its other name is compile-time polymorphism.

PART 8 · PUT IT TOGETHER — WITH NUMBERS

GameScore — fields + a method
that computes, not just prints.

Student.java printed facts. This class computes with them — a method with a return value doing real arithmetic you can check by hand.

MINI PROBLEM · GAMESCORE.JAVA
PROBLEM
Write a class whose method computes with its fields instead of just printing them — then drive it with two players. Save as GameScore.java (+ a Driver.java).
REQUIRE­MENTS
  • Two int fields: basePoints, bonusMultiplier.
  • int totalScore() returning basePoints * bonusMultiplier + 100 — the +100 login bonus.
  • Driver: p1 = 250 × 4, p2 = 600 × 2; println both totals. Notebook first — work both by hand before running.
EXPECTED OUTPUT
1100 then 1300 — same formula, different facts, BODMAS: multiply first, then add.
GameScore.java + Driver — TWO PLAYERS, ONE FORMULA
1public class GameScore
2{
3 int basePoints; // fact 1
4 int bonusMultiplier; // fact 2
5
6 int totalScore() // returns an int — anatomy piece 2 at work
7 {
8 return basePoints * bonusMultiplier + 100; // +100 login bonus
9 }
10}
11
12// inside Driver's main:
13GameScore p1 = new GameScore(); p1.basePoints = 250; p1.bonusMultiplier = 4;
14GameScore p2 = new GameScore(); p2.basePoints = 600; p2.bonusMultiplier = 2;
15System.out.println(p1.totalScore()); // predict BEFORE pressing on
16System.out.println(p2.totalScore()); // this one too
Same formula, different facts. One totalScore() definition in the Method Area; p1 and p2 each carry only their own two ints on the Heap — Part 4's arithmetic again, now with a computing method.
Notebook first (rule of this course): p1 = 250 × 4 + 100. p2 = 600 × 2 + 100. Work both BEFORE unlocking the run below. BODMAS applies: multiply first, then add.

THE RUN · ONE LINE PER PRESS — CHECK AGAINST YOUR NOTEBOOK

TERMINAL · THE MOMENT OF TRUTH
C:\Users\diya\Desktop\java-practice\class-08> javac GameScore.java Driver.java
C:\Users\diya\Desktop\java-practice\class-08> java Driver
1100
1300
p1: 250 × 4 = 1000, + 100 = 1100 · p2: 600 × 2 = 1200, + 100 = 1300. Same method, different objects, different answers — because the method reads EACH object's own fields.

If your notebook says 1100 and 1300 — you just executed Java in your head. That's the whole point of this course.

PART 9 · BIRTH RULES

The constructor — a method with
the class's name and NO return type.

Notice the v7.15 order we took: methods FIRST, constructors second — because a constructor is a special method. Two specialties, that's the whole definition: its name IS the class's name, and it declares no return type — not even void. It runs exactly once per object, at the moment new stamps it.

MINI PROBLEM · STUDENT.JAVA V2
PROBLEM
Upgrade Student with a birth rule: a constructor that fills the facts the moment new stamps the object — no half-empty students, ever.
REQUIRE­MENTS
  • A constructor Student(String n, int m) — the class's own name, no return type, not even void.
  • Body assigns both fields from the parameters.
  • Driver shrinks: new Student("Diya", 91) — born complete, one line per student instead of three.
EXPECTED OUTPUT
Compiles and runs as before — but new Student() (no arguments) now stops compiling: writing your own constructor withdraws Java's free default one.
Student.java v2 — NOW WITH A BIRTH RULE
1public class Student
2{
3 String name;
4 int marks;
5
6 Student(String n, int m) // class's name, NO return type
7 {
8 name = n; // fill the facts at birth
9 marks = m;
10 }
11}
12
13// driver, before: 3 lines per student. Now:
14Student s1 = new Student("Diya", 91); // born complete, one line
15Student s2 = new Student("Rohit", 84);
Count the savings. Part 4's driver spent 3 lines per student (new + two field assignments) — for the college ERP's 28,000 students that's 84,000 lines of birth paperwork. The constructor makes it 28,000. And nobody can ever forget to set marks.
Where did new Student() go? The no-argument form STOPPED compiling the moment we wrote our own constructor. Java's free default constructor exists ONLY while you define none. Write one — the free one is withdrawn.
Exam definition, one line: a constructor is a special method with the same name as the class and no return type, invoked automatically by new to initialise the object.

BUT WHAT IF YOU INITIALISE NOTHING? · DEFAULTS — ONE ROW PER PRESS

FIELD TYPEDEFAULT VALUEMEANING
int / long / short / byte0numeric zero
double / float0.0numeric zero, decimal flavour
booleanfalsethe "no" state
Any object type (String, Student…)nullpoints at NOTHING — touch it and the program dies at runtime

Fields get these automatically — LOCAL variables inside methods get NOTHING and javac refuses to read them uninitialised. Fields forgive; locals don't. That asymmetry is a favourite 2-marker.

null is the default you'll meet again.

A Student made without setting name prints null scored 0 — no crash, just silent wrong data. Part 12's debugging activity is EXACTLY this disease. Constructors exist so objects are never born half-empty.

PART 10 · TWO IDEAS, MULTIPLIED

Constructor overloading —
many ways to be born.

Part 7 said methods overload by parameter shape. Part 9 said a constructor IS a method. Multiply the two: constructors overload too — one class, several birth certificates. This is the exact heart of Lab 1's Exercise 1.

MINI PROBLEM · STUDENT.JAVA V3
PROBLEM
Give Student three ways to be born — constructor overloading, mirroring the real admission desk: walk-in, named applicant, fully enrolled.
REQUIRE­MENTS
  • Student() — fills OUR defaults: "UNREGISTERED", 0.
  • Student(String n) — name known, marks 0.
  • Student(String n, int m) — fully registered.
  • Three distinct fingerprints: (), (String), (String,int) — Part 7's rule, applied to births.
EXPECTED OUTPUT
In JShell: new Student().name"UNREGISTERED" · new Student("Ananya").marks0 · new Student("Diya", 91).marks91.
Student.java v3 — THREE BIRTH CERTIFICATES
1public class Student
2{
3 String name; int marks;
4
5 Student() // fingerprint: ()
6 { name = "UNREGISTERED"; marks = 0; }
7
8 Student(String n) // fingerprint: (String)
9 { name = n; marks = 0; }
10
11 Student(String n, int m) // fingerprint: (String,int)
12 { name = n; marks = m; }
13}
14
15// all three now compile AND run:
16Student a = new Student(); // walk-in, no papers yet
17Student b = new Student("Ananya"); // name known, marks pending
18Student c = new Student("Diya", 91); // fully registered
THREE BIRTHS, VERIFIED

C:\Users\diya\Desktop\java-practice\class-08> javac Student.java

C:\Users\diya\Desktop\java-practice\class-08> jshell

jshell> /open Student.java

jshell> new Student().name

$1 ==> "UNREGISTERED"

jshell> new Student("Ananya").marks

$2 ==> 0

jshell> new Student("Diya", 91).marks

$3 ==> 91

javac first, always. Then one probe per birth certificate: the no-arg form fills OUR defaults, the partial form zeroes marks, the full form takes both. Three fingerprints, three behaviours — verified without a driver.

The compiler picks the constructor the SAME way it picked greet() in Part 7 — by the argument shape at the new site. Zero args picks line 5. One String picks line 8. String + int picks line 11. Nothing new to learn; the fingerprint rule just applies to births too.
Why three? Real admission desks meet all three students: the walk-in enquiry, the applicant with a name, the enrolled student with marks. Overloaded constructors mirror the real intake paths — that's the design smell test for Lab 1: each constructor should describe a REAL way the object enters your system.
Note line 6 vs Part 9's warning: writing our own no-arg constructor brought the new Student() form BACK — but now WE control its defaults ("UNREGISTERED", 0), not Java's silent null/0.

The Lab 1 preview, in one sentence: Exercise 1 asks for a Book class with exactly this pattern — one all-fields constructor, one partial constructor that fills the gap with a default. You have now seen the whole trick; the lab just changes the nouns.

PART 11 · THE OBJECT'S OWN NAME FOR ITSELF

this — "me, the object
currently running this code."

Parts 9–10 dodged a problem by renaming parameters n and m. Professionals don't dodge — they write String name and resolve the clash with this: the object's built-in reference to itself.

MINI PROBLEM · STUDENT.JAVA V4
PROBLEM
Rewrite the constructor with professional parameter names — String name, int marks — and resolve the field/parameter clash with this instead of dodging it with n and m.
REQUIRE­MENTS
  • Parameters named exactly like the fields — they will shadow them inside the braces.
  • this.name = name; and this.marks = marks; — left side field, right side parameter.
  • Narrate line 5 aloud once: "THIS object's name takes the value of the parameter name."
EXPECTED OUTPUT
Identical behaviour to v2 — the change is professionalism, not function. Omit this. and the assignment becomes parameter = parameter: compiles, does nothing (Part 12's disease).
Student.java v4 — PROFESSIONAL NAMES, this RESOLVES
1 String name; int marks;
2
3 Student(String name, int marks) // parameters SHADOW the fields
4 {
5 this.name = name; // MY name = the handed-in name
6 this.marks = marks; // MY marks = the handed-in marks
7 }
The shadow rule: inside line 3's braces, the bare word name means the PARAMETER — the nearer declaration wins. The field is temporarily hidden ("shadowed"). this.name pushes past the shadow to the object's own field.
Read line 5 aloud, exactly once, exactly right: "THIS object's name takes the value of the parameter name." Left side: field. Right side: parameter. If you can narrate that, Part 12's bug will take you 10 seconds.
this also lets methods hand out their owner: later classes use return this; and helper(this). For today: this = the current object, full stop.

SELF-STUDY SUBPAGE · this() — CONSTRUCTOR CALLS CONSTRUCTOR

Part 10's three constructors repeat themselves. this() deletes the repetition.

MINI PROBLEM · STUDENT.JAVA — this() CHAIN
PROBLEM
Part 10's three constructors each assign every field — three copies of the same logic. Delete the repetition: chain the two smaller constructors to the one worker with this(...).
REQUIRE­MENTS
  • Student() forwards: this("UNREGISTERED", 0);
  • Student(String name) forwards: this(name, 0);
  • Only Student(String, int) — the worker — touches the fields.
  • Iron rule: a this() call must be the first statement in its constructor.
EXPECTED OUTPUT
In JShell, new Student().name"UNREGISTERED" — the no-arg constructor holds zero assignments of its own, yet the name arrives filled. The chain worked.
BEFORE / AFTER — THE CHAIN
1// BEFORE (Part 10): every constructor assigns every field — 3 copies of the logic
2
3// AFTER: two forward, ONE does the work
4 Student() { this("UNREGISTERED", 0); } // forwards to the worker
5 Student(String name) { this(name, 0); } // forwards to the worker
6 Student(String name, int marks) // the ONE worker
7 {
8 this.name = name; this.marks = marks;
9 }
this(...) = call a SIBLING constructor, chosen — as always — by fingerprint. Line 4's this("UNREGISTERED", 0) matches the (String,int) sibling. Same resolution rule, third appearance today.
The iron rule: a this() call must be the FIRST statement in the constructor — javac rejects it anywhere else. One chain, one worker, zero duplicated logic: cohesion again.
Why bother? When Lab 1's Book gains a 4th field, the BEFORE version needs 3 edits; the AFTER needs 1 (the worker). Multiply by a codebase with 400 classes — this() is maintenance arithmetic, not style.
PROVE THE CHAIN FORWARDS

C:\Users\diya\Desktop\java-practice\class-08> javac Student.java

C:\Users\diya\Desktop\java-practice\class-08> jshell

jshell> /open Student.java

jshell> new Student().name

$1 ==> "UNREGISTERED"

The no-arg constructor holds ZERO assignment lines of its own — yet the name arrives filled. Proof the call travelled the chain: () forwarded to (String,int), the one worker did the work.

Don't confuse the two spellings.

this.name — a reference to MY field. this(...) — a call to MY sibling constructor. Same keyword, dot versus parentheses, completely different jobs. Exams love printing both in one snippet.

PART 12 · ACTIVITY — NOTEBOOK FIRST

Debug it: every student
prints null.

TASK A junior wrote the constructor below. Every student card prints null scored 91 — the marks are right, the names are ALL null. In your notebook: (a) name the exact line that's broken, (b) explain WHY it compiles yet does nothing, (c) write the one-token fix.

Student.java — THE PATIENT
1public class Student
2{
3 String name; int marks;
4
5 Student(String name, int m)
6 {
7 name = name; // the junior swears this line is fine
8 marks = m;
9 }
10}
THE SYMPTOM — IT COMPILES, IT RUNS, IT'S WRONG

C:\Users\diya\Desktop\java-practice\class-08> javac Student.java CardDriver.java

C:\Users\diya\Desktop\java-practice\class-08> java CardDriver

null scored 91

null scored 84

javac raised ZERO errors — that is the whole trap. The marks arrive; every name is null. Diagnose it in your notebook before unlocking.

All three answers in your notebook first — (a), (b) and (c).

SOLUTION SHEET · THE null DISEASE
  • (a) THE LINELine 7. name = name; — marks (line 8) works only because the parameter is called m, so no clash exists there.
  • (b) WHYPart 11's shadow rule: inside the constructor, BOTH names mean the parameter — the nearer declaration wins. Line 7 assigns the parameter to itself: perfectly legal, completely useless. The field is never touched, keeps its Part-9 default for a String: null.
  • (c) THE FIXOne token: this.name = name; — "MY name = the handed-in name." Left side field, right side parameter, shadow defeated.
  • MORALIt compiled. It ran. It was still wrong. Compiling proves grammar, not meaning — the most important sentence you'll carry into Lab 1's debugging section.

PART 13 · BEFORE YOU GO

Pack the toolkit —
Lab 1 grades every item in it.

TODAY'S TOOLKITTHE ONE LINE THAT EARNS THE MARKS
ClassFacts (fields) + operations (methods) in one named unit; compiles without main, refuses to RUN without it.
newStamps one object per call: 28,000 objects ≈ 672 KB of facts, still ONE 60-byte method definition.
SignatureName + parameter types/order/count. NOT the return type, NOT parameter names — two methods can't differ by return type alone.
OverloadingSame name, different fingerprints, resolved by the compiler at compile time — greet(3,"Diya") and greet('D') both FAIL.
ConstructorA special method: the class's name, NO return type (not even void), runs once per new. Write one and the free default is withdrawn.
DefaultsFields: 0 / 0.0 / false / null. Locals: nothing — javac refuses. Fields forgive; locals don't.
thisthis.name = my field (defeats the shadow) · this(...) = sibling constructor call, FIRST statement only.
YOUR FOLDER AFTER THIS CLASS — CHECK BEFORE YOU LEAVE
Desktop\java-practice\class-08\
Student.java <- v4 is the keeper · 3 ctors + this() chain + printCard
Student.class <- javac made it
CampusDriver.java <- s1/s2 · two objects, one blueprint
CampusDriver.class
Greeter.java <- three greet() fingerprints
Greeter.class
GameScore.java <- totalScore() · 1100 / 1300 predictions
GameScore.class
Driver.java <- runs the two players
Driver.class
Same root as always. Lab 0 built java-practice\lab-00\; Classes 2–4 added class-02\ class-03\ class-04\; Classes 5–7 added nothing (concept classes). Now mkdir class-08 grows the SAME tree — one root, one folder per coding class, forever.

The v7.15 order, one last time: methods first, constructors second — because a constructor IS a method with two specialties. Every rule you learned once (anatomy, signature, overloading) applied twice. That's not coincidence; that's the syllabus audit doing its job.

OBJECT ORIENTED PROGRAMMING THROUGH JAVA · CLASS 8 OF 60 · PART CVCE · K TRISHAANK