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.
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
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
Asha: 82 Ravi: 0
Rejecting invalid objects
25.5 C = 77.9 F Rejected: -300.0 is below absolute zero
More examples
Chaining, copy constructors and initialisation order
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 toPizza("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 changingddoesn't changec. madeis 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:
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
Prefer
Without this, both names refer to the parameter, so the field is never set and stays null.
Giving a constructor a return type
Avoid
Prefer
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
- 1Write a
Timeclass with constructorsTime(h, m)andTime(minutes)that validate their input. - 2Add 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?