Skip to content

Java OOP

0/36 lessons · 0% complete

— XP

Java OOP · Module 3

What a constructor really is

Syntax, the default constructor, and the `this` keyword

20m50 XP
→→→

What you'll be able to do

  • Write a parameterised constructor with the correct syntax
  • Explain what the invisible default constructor does and when it disappears
  • Use `this` to separate a parameter from a field
  • State three differences between a constructor and a method
1

Constructors

A constructor guarantees a valid object

In Module 2 you created an object and then hoped somebody remembered to fill its fields. A constructor removes the hoping.

A constructor is a special block that runs once, automatically, while the object is being created by new. Its job is to put the object into a usable state before anyone else can touch it. Two syntax rules and you know constructors: 1. Its name is exactly the class name. 2. It has no return type — not even void.

Registering a newborn

A baby does not leave the hospital without a name on the birth certificate. Without a constructor, objects leave the hospital anonymous: name is null, balance is 0.0, and the bug shows up three screens later. The constructor is the form you must fill in before the object is released.

The same class, before and after

Module 2 style

create, then remember to fill

Main.java
1Student s = new Student();
2s.name = "Sara";
3s.age = 20;
4// forget one line = broken object
  • Three statements to create one student
  • Nothing forces the caller to set anything
  • An invalid object exists for a while — and can be used

With a constructor

valid on arrival

Main.java
1Student s = new Student("Sara", 20);
2// impossible to forget:
3// the compiler demands both values
  • One statement, one complete object
  • The compiler enforces the required data
  • Validation can live in one place (Module 4)

Reading a constructor

Main.java
1class Student {
2 String name;
3 int age;
4
5 Student(String name, int age) {
6 this.name = name;
7 this.age = age;
8 }
9}
Student(String name, int age) {
Same name as the class, no return type → this is a constructor. The parameters are the data the object cannot live without.
this.name = name;
this.name is the field of the object being built; bare name is the parameter. Without this. both names would mean the parameter.
this.age = age;
Same pattern. After these two lines the object is fully formed, and only then does new hand back the reference.
Two students, one constructor

Add a third student with your own name and age, then try calling `new Student()` with no arguments and read the compiler error.

Output
Press Run to execute this example.

Prove it — coding challenges

2

Default Constructor

The constructor you never wrote

`new Student()` worked in Module 2 even though no constructor existed. Someone wrote one for you.

If a class declares no constructor, the compiler inserts an invisible default constructor: no parameters, empty body. That is why new Student() compiled — and why every field was left at its type default. The moment you declare *any* constructor, the compiler stops inserting it. This surprises everyone once: adding Student(String name, int age) makes the old new Student() calls stop compiling.

What the compiler adds when you write nothing
Main.java
1class Student {
2 String name;
3 int age;
4
5 // invisible, added by the compiler:
6 // Student() { }
7}
An empty body, so fields keep their defaults: null, 0, 0.0, false.

Want both? Write both.

If you still need new Student() after adding a parameterised constructor, declare the no-argument one yourself — usually with sensible defaults such as this("unknown", 0);. You will do exactly that in the next lesson.

3

The this Keyword

`this`: the object talking about itself

Inside any instance method or constructor, this is a reference to the object the code is running on. You have used it implicitly all along: writing name inside a method is short for this.name. You only *need* to write this. when a parameter has the same name as the field — which is the normal convention in constructors, because Student(String name, int age) reads better than Student(String n, int a).

The classic shadowing bug

Run it and explain the 0. Then fix line 6 by adding `this.` and run again.

Output
Press Run to execute this example.

`x = x;` compiles and does nothing

The parameter shadows the field, so the assignment copies the parameter onto itself and the field keeps its default. No error, no warning, wrong data. This is one of the most common beginner bugs — and a favourite exam question.

4

Constructor vs Method

Constructor vs method

ConstructorMethod
Nameexactly the class nameany verb you like
Return typenone (not even void)required
Calledautomatically by newexplicitly by you
How oftenonce per objectas often as you want
Purposeinitialise stateuse or change state
Inherited?no (but see super() in Module 6)yes

The trap: adding `void` in front of a constructor turns it into an ordinary method with a strange name.

Common mistakes

Wrongvoid Student(String name) { this.name = name; }
WhyWith a return type it is a *method* named Student, so the class still only has the default constructor and `new Student("Sara")` will not compile.
FixRemove `void`: Student(String name) { this.name = name; }
WrongStudent(String name) { name = name; }
WhyThe parameter shadows the field; the field stays null.
FixUse `this.name = name;`
WrongAdding a parameterised constructor and still calling `new Student();` elsewhere.
WhyThe compiler no longer generates the no-argument constructor.
FixDeclare the no-argument constructor explicitly if you still need it.

Lesson playground

Free practice

A Rectangle whose constructor guarantees both sides. Add a constructor that takes one side and builds a square.

Output
Press Run to execute this example.

Check understanding

Quiz

Question 1 of 5

The constructor only sets one field. What will happen when this code runs?

Main.java
1class Book {
2 String title;
3 double price;
4
5 Book(String title) {
6 this.title = title;
7 }
8
9 void show() {
10 System.out.println(title + " costs " + price);
11 }
12}
13
14public class Main {
15 public static void main(String[] args) {
16 Book b = new Book("Java");
17 b.show();
18 }
19}

Summary

  • A constructor has the class name, no return type, and runs once during `new`.
  • The invisible default constructor exists only while you declare none.
  • `this.field = param;` is how you assign when names collide; `param = param;` silently does nothing.
  • Constructors initialise; methods operate. Adding `void` turns one into the other.