Sub topic 12
Constructors and Object Initialization
What You Will Learn
When you create an object in Java, something has to set it up. The new object needs a name, a starting size, or any other values its data fields should hold. The piece of code that does this setup is called a constructor.
A constructor is a special method in a class. Its name is exactly the same as the class name, and it has no return type at all — not even void. Java calls the constructor automatically when you use the keyword new.
By the end of this chapter you will be able to:
- Explain what a constructor is and when Java runs it
- Write a class with a default constructor and with parameterized constructors
- Use the
thiskeyword to refer to the current object's fields - Overload constructors so a class can be created in several ways
- Chain constructors with
this(...) - Follow the exact order of initialization steps when an object is created
This chapter assumes you have read the earlier chapters on Classes and Objects and Methods. You should know how to declare a class with fields, write a method, and create an object with new.
Why Constructors Matter
A class is a blueprint. An object is a real thing built from that blueprint. But a freshly built object can be awkward if its fields are left at default values like 0 or null. The constructor's job is to move the object into a good starting state.
Think of a car factory: the blueprint says every car has four wheels and an engine, but each real car is given a specific paint color and serial number as it comes off the line. That step is construction.
class Car {
String color;
int wheels;
Car(String c) {
color = c;
wheels = 4;
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("red");
System.out.println(myCar.color + " car with " + myCar.wheels + " wheels");
}
}Running this prints red car with 4 wheels. The line new Car("red") does three things: it allocates memory for a new Car object, it runs the constructor with the argument "red", and it returns a reference to the finished object, which is stored in myCar.
Anatomy of a Constructor
class Dog {
String name;
Dog(String name) { // constructor: same name as class, no return type
this.name = name;
}
void speak() {
System.out.println(name + " says woof");
}
}Three rules identify a constructor:
- The constructor name matches the class name exactly, including capitalization.
- A constructor has no return type — no
void, nothing. If you accidentally add a return type, Java treats it as an ordinary method with the same name as the class, and it will never be called automatically. This is a common beginner mistake. - A constructor may take parameters, just like a normal method.
The `this` Keyword
this means "the current object." Inside the constructor, the parameter name and the field name have the same identifier. To say "the field that belongs to this object," you write this.name.
Dog(String name) {
this.name = name; // field on the left, parameter on the right
}If the parameter had a different name, this would not be needed:
Dog(String n) {
name = n; // unambiguous, so this. is optional
}Many Java programmers prefer to keep the names identical and always use this., because it makes the intent obvious. this also works in ordinary methods, not just constructors.
Default Constructors
If you write a class with no constructor at all, Java quietly gives you one. It is called the default constructor (sometimes "the no-argument constructor"). It takes no parameters and does nothing except let the object exist with default field values.
class Point {
int x;
int y;
// no constructor written — Java provides Point() automatically
}
public class Main {
public static void main(String[] args) {
Point p = new Point(); // works because of the default constructor
System.out.println(p.x + ", " + p.y); // prints 0, 0
}
}Important rule: once you write any constructor yourself, the default one disappears. If Point has a constructor Point(int x, int y), then new Point() no longer compiles — unless you also write a Point() yourself.
Constructor Overloading
Overloading means having several constructors with the same name but different parameter lists. This gives users of your class several convenient ways to create it.
class Rectangle {
int width;
int height;
Rectangle() { // no arguments: a 1x1 square
this(1, 1); // calls the two-argument constructor below
}
Rectangle(int side) { // one argument: a square
this(side, side);
}
Rectangle(int width, int height) { // two arguments: the full version
this.width = width;
this.height = height;
}
}
public class Main {
public static void main(String[] args) {
Rectangle a = new Rectangle();
Rectangle b = new Rectangle(5);
Rectangle c = new Rectangle(3, 4);
System.out.println(a.width * a.height); // 1
System.out.println(b.width * b.height); // 25
System.out.println(c.width * c.height); // 12
}
}Java picks which constructor to run by matching the number and types of the arguments you pass.
Chaining Constructors with `this(...)`
Notice this(1, 1) in the example above. Calling this(...) inside a constructor runs another constructor of the same class. This avoids duplicating setup code: small constructors delegate to the biggest one.
Two rules apply:
- The
this(...)call must be the first statement in the constructor. - You cannot chain to the same constructor and create an infinite loop, and you cannot call
this(...)twice.
The Order of Initialization
What exactly happens when Java executes new Rectangle(3, 4)? The steps run in this order:
- Memory for the new object is allocated, and every field is set to its default value:
0for numbers,falsefor booleans,nullfor object references. - Field initializers and initialization blocks run, in the order they appear in the class. (For example,
int size = 10;on a field line.) - The constructor body runs, after any
this(...)or superclass constructor call.
Constructors and Inheritance: A First Look
The next chapter covers inheritance in detail, but one initialization fact belongs here. When you create a subclass object, the superclass constructor runs first. If you do not call it explicitly, Java inserts an invisible call to the superclass's no-argument constructor.
class Animal {
Animal() {
System.out.println("Animal created");
}
}
class Dog extends Animal {
Dog() {
// super(); is inserted here automatically
System.out.println("Dog created");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
// prints:
// Animal created
// Dog created
}
}If the superclass has only constructors that take arguments, the subclass must call one of them explicitly with super(...), as the first statement. You will meet this again in the chapter on inheritance.
Common Errors and How to Fix Them
| Error message | Usual cause | Fix |
|---|---|---|
| `constructor X in class X cannot be applied to given types` | You passed arguments that do not match any constructor's parameter list | Check the constructors you wrote; add one with the right parameter types, or pass matching arguments |
| `method X in class X cannot be applied to given types` when calling `new X()` | You wrote a constructor with parameters, so the default no-argument constructor no longer exists | Write an explicit no-argument constructor, or pass the required arguments |
| Constructor "seems to be ignored" | You accidentally gave it a return type like `void`, so it became a normal method | Remove the return type; a constructor has none |
| `call to this must be first statement in constructor` | You placed `this(...)` after other code | Move the `this(...)` call to the first line |
A Worked Example: Putting It All Together
class BankAccount {
String owner;
double balance;
BankAccount() {
this("unknown", 0.0);
}
BankAccount(String owner) {
this(owner, 0.0);
}
BankAccount(String owner, double balance) {
this.owner = owner;
this.balance = balance;
}
void print() {
System.out.println(owner + " has balance " + balance);
}
}
public class Main {
public static void main(String[] args) {
new BankAccount().print(); // unknown has balance 0.0
new BankAccount("Asha").print(); // Asha has balance 0.0
new BankAccount("Ben", 250.50).print(); // Ben has balance 250.5
}
}Every constructor funnels into the full three-argument one, so the assignment logic lives in exactly one place.
Exercises
Exercise
What is the difference between a constructor and a normal method?
Show answer
A constructor has the same name as the class and no return type, and Java runs it automatically when the object is created with new. A normal method has its own name, declares a return type, and must be called explicitly on an object.
Exercise
The class Timer has only the constructor Timer(int start). Does new Timer() compile? Why or why not?
Show answer
No. Once you write any constructor, Java stops providing the default no-argument constructor, so new Timer() has nothing to match. Add an explicit Timer() constructor (or a this(...) chain) if you need it.
Exercise
In the constructor Point(int x, int y) { this.x = x; this.y = y; }, what would happen if you removed the this. keywords?
Show answer
The assignments would become x = x; and y = y; — each parameter assigned to itself. The fields would stay at their default value 0, and no error would be reported.
Exercise
Rewrite Rectangle(int width, int height) from this chapter so that its constructor chain is: Rectangle() calls Rectangle(int side), which calls Rectangle(int width, int height). Write all three constructors.
Show answer
Rectangle() { this(1); }, Rectangle(int side) { this(side, side); }, Rectangle(int width, int height) { this.width = width; this.height = height; } — each this(...) call is the first statement of its constructor.