Skip to content

Module 5 · Classes and Objects — topic 2 of 4

Constructors and this

Initialising objects with constructors, the default constructor, overloaded constructors and constructor chaining with this(...), and the this reference.

Beginner 14 min read·Lesson 17 of 39 in Java Programming

Learning objectives

  • Write constructors that establish valid objects
  • Overload constructors and chain them with this(...)
  • Use this to refer to fields shadowed by parameters

Definition

A constructor is a special method with the same name as its class and no return type that runs when an object is created with new, initialising its fields. this refers to the current object.

Introduction

Setting fields one by one after new is tedious and dangerous — it is easy to forget one and end up with a half-built object. A constructor makes creating and initialising a single step: new Student("Asha", 82).

Why it matters

Constructors are where you guarantee that every object starts in a valid state, for example rejecting a negative price.

Overloaded constructors make classes convenient to use with sensible defaults.

Detailed explanation

A constructor has the class's name and no return type (not even void). It runs once per object, immediately after the fields receive their default values and field initialisers run.

Default constructor. If you write no constructor, the compiler adds a public no-argument one that does nothing. As soon as you write any constructor, that default disappears — new Student() then fails to compile unless you also declare a no-argument constructor.

this. Inside an instance method or constructor, this is a reference to the current object. It is needed when a parameter has the same name as a field: this.name = name;.

Overloading and chaining. A class can have several constructors with different parameters. One constructor can call another with this(...), which must be the first statement. Put the real initialisation logic in the most complete constructor and let the others delegate to it.

Validation. Throw an exception such as IllegalArgumentException from a constructor to refuse invalid data; then no invalid object can ever exist.

Copy constructors take another object of the same class and copy its fields — a simple, explicit way to duplicate objects.

Syntax

Java
class Product {
private final String name;
private double price;
Product(String name, double price) {
if (price < 0) throw new IllegalArgumentException("negative price");
this.name = name; // this.field = parameter
this.price = price;
}
Product(String name) {
this(name, 0.0); // chain to the other constructor
}
}
  • this(...) must be the first statement in a constructor.
  • final fields must be assigned exactly once, in every constructor.
  • Constructors are not inherited (see Inheritance).

Code examples

Constructors and this

Java
public class Main {
public static void main(String[] args) {
Student a = new Student("Asha", 82);
Student b = new Student("Ravi");
System.out.println(a);
System.out.println(b);
}
}
class Student {
String name;
int marks;
Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
Student(String name) {
this(name, 0); // new students start with 0 marks
}
@Override public String toString() { return name + ": " + marks; }
}
Output
Asha: 82
Ravi: 0

Rejecting invalid objects

Java
public class Main {
public static void main(String[] args) {
System.out.println(new Temperature(25.5));
try {
new Temperature(-300);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}
class Temperature {
final double celsius;
Temperature(double celsius) {
if (celsius < -273.15) throw new IllegalArgumentException(celsius + " is below absolute zero");
this.celsius = celsius;
}
@Override public String toString() { return celsius + " C = " + (celsius * 9 / 5 + 32) + " F"; }
}
Output
25.5 C = 77.9 F
Rejected: -300.0 is below absolute zero

More examples

Chaining, copy constructors and initialisation order

Java
public class Main {
public static void main(String[] args) {
Pizza a = new Pizza();
Pizza b = new Pizza("large");
Pizza c = new Pizza("medium", "paneer", "onion");
Pizza d = new Pizza(c);
d.addTopping("olives");
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println("pizzas made: " + Pizza.made);
}
}
class Pizza {
static int made = 0;
private final String size;
private final java.util.List<String> toppings = new java.util.ArrayList<>(); // field initialiser runs first
Pizza() { this("regular"); }
Pizza(String size, String... toppings) {
this.size = size;
for (String t : toppings) this.toppings.add(t);
made++;
}
Pizza(Pizza other) { // copy constructor
this(other.size);
this.toppings.addAll(other.toppings); // copy the list, don't share it
}
void addTopping(String t) { toppings.add(t); }
int price() { return switch (size) { case "large" -> 400; case "medium" -> 300; default -> 200; } + 40 * toppings.size(); }
@Override public String toString() { return size + " " + toppings + " Rs " + price(); }
}
Output
regular [] Rs 200
large [] Rs 400
medium [paneer, onion] Rs 380
medium [paneer, onion, olives] Rs 420
pizzas made: 4

Step-by-step explanation

  • new Pizza() delegates to Pizza("regular"), which calls the varargs constructor with no toppings.
  • The field initialiser toppings = new ArrayList<>() runs before each constructor body, so the list is always ready.
  • The copy constructor chains to this(other.size) and then copies the toppings into its *own* list, so changing d doesn't change c.
  • made is a static field shared by all pizzas; every constructor path increments it exactly once because they all end in the varargs constructor.
  • price() uses a switch expression for the base price and adds 40 per topping.

Expected output

Running “Chaining, copy constructors and initialisation order” prints exactly:

TextOutput
regular [] Rs 200
large [] Rs 400
medium [paneer, onion] Rs 380
medium [paneer, onion, olives] Rs 420
pizzas made: 4

Practical applications

  • Creating immutable value objects such as Money or Date with all fields set at once
  • Validating configuration objects when they are constructed
  • Providing convenient constructors with defaults in library classes

Best practices

  • Validate arguments in the constructor so invalid objects can't exist.
  • Keep one 'main' constructor and chain the others to it.
  • Make fields final when they never change after construction.

Common mistakes

Forgetting this when names shadow fields

Avoid

Student(String name) { name = name; }

Prefer

Student(String name) { this.name = name; }

Without this, both names refer to the parameter, so the field is never set and stays null.

Giving a constructor a return type

Avoid

void Student(String name) { this.name = name; }

Prefer

Student(String name) { this.name = name; }

With a return type it becomes an ordinary method named Student, and new Student("x") no longer compiles.

Important notes

  • Calling overridable methods from a constructor is risky, because a subclass's fields aren't initialised yet when the superclass constructor runs.
  • Records (module 7) generate the constructor, accessors, equals, hashCode and toString for simple data classes.

Key takeaways

  • Constructors initialise new objects and have no return type.
  • Writing any constructor removes the implicit no-argument constructor.
  • this refers to the current object; this(...) chains constructors and must come first.

Try it yourself

  1. 1
    Write a Time class with constructors Time(h, m) and Time(minutes) that validate their input.
  2. 2
    Add a copy constructor to a class holding an array, and prove the copy is independent.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

7 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is true about constructors?
  • BeginnerA class declares only `Car(String model)`. What happens with `new Car()`?
  • BeginnerWhat is printed?
Practise this topic