These are the notes for Java episode 15. In episode 14 we invented classes and objects, but every student still took four lines to set up, and one forgotten line gave us a half-filled object that crashed later. Today we fix that with constructors, and on the way we meet the this keyword, the default constructor, constructor overloading, constructor chaining with this(...) and the copy constructor. Every example below runs as-is in the SyntaxPilot compiler, with its real output from javac 21.
The problem: the half-filled object
Last episode, making a student was a four-step job: new Student(), then fill each field by hand. To keep things small, a Student here has just a name and a total, plus a print() method that prints the name in capitals (like on a report card).
class Student {
String name;
int total;
void print() {
System.out.println(name.toUpperCase() + " " + total);
}
}
public class Main {
public static void main(String[] args) {
Student a = new Student();
a.name = "Diya";
a.total = 274;
a.print();
Student b = new Student();
b.total = 255;
b.print();
}
}
DIYA 274
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because "this.name" is null
at Student.print(Main.java:6)
at Main.main(Main.java:19)
Somebody forgot b.name = .... Java did not complain: the program crashed later, in print(), far from the real mistake.
Why it failed
new Student()gives a blank object. Every field holds its default value:nullfor objects likeString,0for numbers,falseforboolean.- Filling the fields is a separate, optional job. Nothing forces you to do it.
- 40 students = 160 setup lines, and every one is a chance to forget something.
What we want is a rule: you cannot get a student without giving its details. Creating and filling must be one step.
Real-life fix: the school admission desk
| School admission | Java |
|---|---|
| The admission form (name, class, parents' phone) | the constructor's parameters (String name, int total) |
| The admission desk checks every box, for every new student | the constructor runs on every new |
| You get a roll number only when the form is complete | the object is ready and valid from the moment it exists |
Your first constructor
A constructor is a special block of code inside a class that runs automatically when an object is created with new. Its job is to put the new object in a valid state.
class Student {
String name;
int total;
Student(String n, int t) {
name = n;
total = t;
}
void print() {
System.out.println(name.toUpperCase() + " " + total);
}
}
public class Main {
public static void main(String[] args) {
Student a = new Student("Diya", 274);
Student b = new Student("Aarav", 255);
a.print();
b.print();
}
}
DIYA 274
AARAV 255
One line per student instead of four, and forgetting the name is now impossible: new Student(255) does not even compile.
Constructor rules
- Its name is exactly the class name (
Student, capital S). - It has no return type, not even
void. - You never call it by name: it runs by itself on
new, exactly once per object. - Its job: make sure every object starts complete and valid.
Trap: void Student(...) is not a constructor
Add void and it becomes an ordinary method that happens to share the class name:
void Student(String n, int t) {
name = n;
total = t;
}
Main.java:17: error: constructor Student in class Student cannot be applied to given types;
Student a = new Student("Diya", 274);
^
required: no arguments
found: String,int
reason: actual and formal argument lists differ in length
With no real constructor written, Java only knows the empty default one (see below), so new Student("Diya", 274) has nothing to match.
The name = name bug (shadowing)
n and t are poor names. Let's name the parameters properly:
Student(String name, int total) {
name = name;
total = total;
}
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because "this.name" is null
at Student.print(Main.java:11)
at Main.main(Main.java:19)
No compile error, no warning, and the name is still null. Inside the constructor there are now two things called name: the parameter and the field. When names clash, Java uses the closest one, the parameter. So name = name copies the parameter into itself and the field is never touched. A local variable or parameter hiding a field with the same name is called shadowing.
this means "my"
| In a classroom | In Java |
|---|---|
| Diya says "my bag": Diya's bag | this.name inside Diya's object |
| Aarav says "my bag": Aarav's bag | this.name inside Aarav's object |
| "bag" alone: the one in your hand | plain name: the closest name, the parameter |
this is a reference to the current object: the object being built (in a constructor) or used (in a method) right now.
On the stack and the heap
new Student("Diya", 274)makes a blank object on the heap:name = null,total = 0.- The constructor runs with its own frame on the stack: parameters
name = "Diya",total = 274, plus a hidden referencethispointing at the new object. name = name;changes only the parameter on the stack. The heap still saysnull.this.name = name;follows thethisarrow and sets the object's field.- The constructor ends, its frame disappears, and
newhands the object's address toa. new Student("Aarav", 255)creates a new object with a newthis: same code, different object.
The fix
Student(String name, int total) {
this.name = name;
this.total = total;
}
DIYA 274
AARAV 255
this.field = parameter is how almost every Java constructor is written. And the first error message makes sense now: "this.name" is null meant Aarav's own name field.
Where did new Student() go? The default constructor
If a class has no constructor at all, Java quietly adds one: no parameters, empty body. This is the default constructor, and it's why new Student() worked in episode 14.
The moment you write any constructor yourself, Java stops adding it:
public class Main {
public static void main(String[] args) {
Student a = new Student("Diya", 274);
Student k = new Student();
a.print();
}
}
Main.java:18: error: constructor Student in class Student cannot be applied to given types;
Student k = new Student();
^
required: String,int
found: no arguments
reason: actual and formal argument lists differ in length
1 error
This is a good thing: the desk only accepts complete forms. If you also need a "blank" or "partial" way to create objects, you must write that constructor yourself.
Constructor overloading
A student who joins mid-year has a name but no marks yet. Open a second counter: another constructor with different parameters.
class Student {
String name;
int total;
Student(String name, int total) {
this.name = name;
this.total = total;
}
Student(String name) {
this.name = name;
this.total = 0;
}
void print() {
System.out.println(name.toUpperCase() + " " + total);
}
}
public class Main {
public static void main(String[] args) {
Student a = new Student("Diya", 274);
Student k = new Student("Kabir");
a.print();
k.print();
}
}
DIYA 274
KABIR 0
Several constructors with the same name and different parameter lists is constructor overloading. Java picks the one whose parameters match the arguments you pass, exactly like method overloading (episode 11).
Constructor chaining with this(...)
New rule: a total must be 0 to 500 (5 subjects x 100); anything else is a typo, set to 0 with a warning. If both constructors set the fields, the check gets copy-pasted into both, and one day someone updates one copy and forgets the other.
Real life: the quick counter takes just your name, writes "marks: 0", and forwards you to the main desk, where all the rules live. In Java, this(...) (the word this followed by round brackets) calls another constructor of the same class. Constructors calling each other is constructor chaining.
class Student {
String name;
int total;
Student(String name, int total) {
if (total < 0 || total > 500) {
System.out.println("Bad total: " + name);
total = 0;
}
this.name = name;
this.total = total;
}
Student(String name) {
this(name, 0);
}
void print() {
System.out.println(name.toUpperCase() + " " + total);
}
}
public class Main {
public static void main(String[] args) {
Student a = new Student("Diya", 274);
Student k = new Student("Kabir", 520);
Student m = new Student("Meera");
a.print();
k.print();
m.print();
}
}
Bad total: Kabir
DIYA 274
KABIR 0
MEERA 0
The rules live in one place (the main constructor). Every way of creating a student goes through it.
Rule: this(...) must be the first statement
Student(String name) {
System.out.println("New: " + name);
this(name, 0);
}
Main.java:16: error: call to this must be first statement in constructor
this(name, 0);
^
1 error
Forward first, extra work after:
Student(String name) {
this(name, 0);
System.out.println("New: " + name);
}
Bad total: Kabir
New: Meera
DIYA 274
KABIR 0
MEERA 0
Copy constructor: a photocopy, not a second name
From episode 14: Student b = a; copies the reference, not the object. One object, two names; change it through b and a changes too. To get a real, independent copy, write a constructor that takes another Student:
class Student {
String name;
int total;
Student(String name, int total) {
this.name = name;
this.total = total;
}
Student(Student other) {
this(other.name, other.total);
}
void print() {
System.out.println(name.toUpperCase() + " " + total);
}
}
public class Main {
public static void main(String[] args) {
Student a = new Student("Diya", 274);
Student c = new Student(a);
c.total = 280;
a.print();
c.print();
}
}
DIYA 274
DIYA 280
A quick check of the difference (== compares references):
Student s = new Student("Diya");
Student s2 = s; // same object
Student s3 = new Student(s.name); // a new object
System.out.println((s == s2) + " " + (s == s3)); // true false
Common mistakes (and the real error messages)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
Forgetting a field after new Student() |
java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because "this.name" is null |
Unset fields keep their default (null) |
Use a constructor that takes every required detail |
name = name; in the constructor |
no error; the field stays null |
The parameter shadows the field | this.name = name; |
void Student(String n, int t) |
error: constructor Student in class Student cannot be applied to given types; (required: no arguments, found: String,int) |
void makes it a method, not a constructor |
Constructors have no return type |
new Student() after writing Student(String, int) |
error: constructor Student in class Student cannot be applied to given types; (required: String,int, found: no arguments) |
No default constructor once you write your own | Pass the details, or add a no-argument constructor |
A statement before this(...) |
error: call to this must be first statement in constructor |
Forwarding must happen first | Put this(...) on the first line |
Expecting b = a to copy |
changing b changes a |
Only the reference was copied | new Student(a) with a copy constructor |
Mini project: train tickets
A Ticket class with three ways to create it: a full ticket, a waiting-list ticket (no seat yet), and a ticket for a co-passenger copied from another one. All of them chain to one main constructor that checks the fare.
class Ticket {
String passenger;
String train;
String seat;
int fare;
Ticket(String passenger, String train, String seat, int fare) {
if (fare < 0) {
System.out.println("Bad fare for " + passenger);
fare = 0;
}
this.passenger = passenger;
this.train = train;
this.seat = seat;
this.fare = fare;
}
Ticket(String passenger, String train, int fare) {
this(passenger, train, "WL", fare); // no seat yet: waiting list
}
Ticket(Ticket other, String passenger) {
this(passenger, other.train, other.seat, other.fare);
}
void print() {
System.out.println(passenger + " | " + train + " | " + seat + " | Rs " + fare);
}
}
public class Main {
public static void main(String[] args) {
Ticket t1 = new Ticket("Diya", "12951 Rajdhani", "B2-34", 2450);
Ticket t2 = new Ticket("Aarav", "12951 Rajdhani", 2450);
Ticket t3 = new Ticket(t1, "Meera");
t3.seat = "B2-35";
Ticket t4 = new Ticket("Kabir", "12002 Shatabdi", -100);
t1.print();
t2.print();
t3.print();
t4.print();
}
}
Bad fare for Kabir
Diya | 12951 Rajdhani | B2-34 | Rs 2450
Aarav | 12951 Rajdhani | WL | Rs 2450
Meera | 12951 Rajdhani | B2-35 | Rs 2450
Kabir | 12002 Shatabdi | WL | Rs 0
Notice t3.seat = "B2-35" changed only Meera's ticket: the copy constructor made a new object.
Practice
- Give
Studentanint[] marksfield and a constructorStudent(String name, int[] marks)that works outtotalitself. An empty name should become"Unknown". - Write a
Bookclass (title,author,pages) with three constructors chained withthis(...): all three details; title and author (100 pages); title only (author"Anonymous"). Pages below 1 become 1. - In the quiz class below, remove the line
this(5);. What donew A()andnew A(5)print now?
Solutions
1.
class Student {
String name;
int[] marks;
int total;
Student(String name, int[] marks) {
if (name == null || name.isEmpty()) {
name = "Unknown";
}
this.name = name;
this.marks = marks;
for (int m : marks) {
this.total += m;
}
}
void print() {
System.out.println(name + " " + total);
}
}
public class Main {
public static void main(String[] args) {
Student a = new Student("Diya", new int[]{95, 88, 91});
Student b = new Student("", new int[]{40, 50, 60});
a.print();
b.print();
}
}
Diya 274
Unknown 150
2.
class Book {
String title;
String author;
int pages;
Book(String title, String author, int pages) {
if (pages < 1) {
pages = 1;
}
this.title = title;
this.author = author;
this.pages = pages;
}
Book(String title, String author) {
this(title, author, 100);
}
Book(String title) {
this(title, "Anonymous");
}
void print() {
System.out.println(title + " by " + author + ", " + pages + " pages");
}
}
public class Main {
public static void main(String[] args) {
new Book("Wings of Fire", "A. P. J. Abdul Kalam", 180).print();
new Book("Malgudi Days", "R. K. Narayan").print();
new Book("Panchatantra").print();
new Book("Empty", "Nobody", -5).print();
}
}
Wings of Fire by A. P. J. Abdul Kalam, 180 pages
Malgudi Days by R. K. Narayan, 100 pages
Panchatantra by Anonymous, 100 pages
Empty by Nobody, 1 pages
Note how Book(String title) forwards to the two-argument constructor, which forwards to the main one: a chain of two hops.
- Without
this(5);,new A()prints justB, andnew A(5)printsA5. The constructors no longer call each other.
Quick quiz
What does this print?
class A {
A() {
this(5);
System.out.print("B");
}
A(int x) {
System.out.print("A" + x);
}
}
// in main:
new A();
A. B B. BA5 C. A5B D. A5
Answer
C. A5B. new A() runs A(), whose first line forwards to A(5), which prints A5. Control then returns to A(), which prints B.
Interview questions
- What is a constructor, and how is it different from a method? It runs automatically on
new, has the class's name and no return type, and initialises the object. A method has a return type (orvoid), any name, and is called explicitly. - What is the default constructor? When does Java provide it? A no-argument constructor Java adds only when the class declares no constructors.
- What does
thisrefer to? The current object: the one being constructed, or the one a method was called on. - Why does
name = name;not work in a constructor? The parameter shadows the field, so the parameter is assigned to itself. Usethis.name = name;. - What is constructor chaining? What's the rule for
this(...)? One constructor calling another of the same class withthis(...); the call must be the first statement. - Can a constructor be overloaded? Yes, with different parameter lists. (It cannot be
static, and it is not inherited; more in the inheritance episode.) - What's the difference between
b = aand a copy constructor?b = acopies the reference (one object);new Student(a)creates a second, independent object. - Can a constructor return a value? No. It has no return type;
newgives back the reference to the new object.
Glossary
| Term | Meaning | Example |
|---|---|---|
| object | a thing made from a class, with its own field values (episode 14) | new Student("Diya", 274) |
| field | a variable that belongs to each object | String name; |
| default value | what a field holds if nobody sets it | null, 0, false |
null |
a reference that points to no object | an unset name |
| NullPointerException | the crash when you use a null reference as if it were an object |
name.toUpperCase() with name == null |
| constructor | code with the class's name and no return type that runs on new to set up the object |
Student(String name, int total) { ... } |
| parameter | a named input a constructor or method receives | String name |
| argument | the actual value passed in | "Diya" |
| default constructor | the no-argument constructor Java adds only if you write none | new Student() in episode 14 |
| shadowing | a parameter or local variable hiding a field with the same name | name = name; |
this |
a reference to the current object | this.name = name; |
| stack frame | the block of stack memory for one method or constructor call: its parameters and local variables | the constructor's name, total, this |
| heap | memory where objects live | the Student objects |
| constructor overloading | several constructors with different parameter lists | Student(String) and Student(String, int) |
| constructor chaining | one constructor calling another with this(...) |
this(name, 0); |
| copy constructor | a constructor that builds a new object from an existing one | Student(Student other) |
| reference | the address of an object, stored in a variable | a in Student a = ... |
| validation | checking values make sense before storing them | total < 0 \|\| total > 500 |
Summary
new Student()gives a blank object; forgetting to fill a field leaves its default (null) and crashes later.- A constructor (class name, no return type, runs on
new) makes creating and filling one step, so objects are never half-filled. name = nameis shadowing: the parameter wins.this.name = namesets the current object's field.- Write any constructor and the default constructor disappears.
- Overloading gives several ways to create an object;
this(...)chains them to one main constructor where the rules live, and must be the first statement. - A copy constructor makes a real copy;
b = aonly gives the same object a second name.
Next episode: every student stores its own copy of the school's name, and a counter of students created always says 1. Some things belong to the whole class, not to one object: static members and static blocks.