A constructor runs when you create an object with new. Its job is to give the object a valid starting state. Real classes often need several ways to be created, and subclasses must set up their parent part first. This lesson shows how to chain constructors with this(...) and super(...), how to check arguments, and the exact order in which Java runs static blocks, field initialisers, instance blocks and constructors.
In this lesson you will learn
- Overloaded constructors that chain with
this(...) - Calling a parent constructor with
super(...) - Rejecting bad values inside a constructor
- Static blocks and instance initialiser blocks
- The full order of initialisation, parent and child
You should know classes and objects, inheritance and static and final.
Chaining Constructors
When a class has several constructors, put the real work in one main constructor. The others just fill in default values and pass everything to it with this(...). Then the checks and assignments live in one place.
public class Main {
static class Book {
private final String title;
private final String author;
private final int pages;
Book(String title, String author, int pages) { // the main constructor
if (pages <= 0) throw new IllegalArgumentException("pages must be positive");
this.title = title;
this.author = author;
this.pages = pages;
System.out.println(" main constructor ran for " + title);
}
Book(String title, String author) { // chains to the main one
this(title, author, 100);
System.out.println(" two-argument constructor finished");
}
Book(String title) {
this(title, "Unknown");
System.out.println(" one-argument constructor finished");
}
public String toString() { return title + " by " + author + ", " + pages + " pages"; }
}
static class Ebook extends Book {
private final double sizeMb;
Ebook(String title, String author, int pages, double sizeMb) {
super(title, author, pages); // must be the first statement
this.sizeMb = sizeMb;
}
public String toString() { return super.toString() + ", " + sizeMb + " MB"; }
}
public static void main(String[] args) {
System.out.println("new Book(\"Lalsalu\"):");
Book b = new Book("Lalsalu");
System.out.println(" -> " + b);
System.out.println("new Ebook(...):");
Ebook e = new Ebook("Padma Nadir Majhi", "Manik Bandopadhyay", 180, 1.4);
System.out.println(" -> " + e);
try {
new Book("Empty", "Nobody", 0);
} catch (IllegalArgumentException ex) {
System.out.println("Rejected: " + ex.getMessage());
}
}
}
Output
new Book("Lalsalu"):
main constructor ran for Lalsalu
two-argument constructor finished
one-argument constructor finished
-> Lalsalu by Unknown, 100 pages
new Ebook(...):
main constructor ran for Padma Nadir Majhi
-> Padma Nadir Majhi by Manik Bandopadhyay, 180 pages, 1.4 MB
Rejected: pages must be positive
new Book("Lalsalu")calls the one-argument constructor. It calls the two-argument one, which calls the main one. The output shows the main constructor finishing first, then each caller finishing in turn.this(...)andsuper(...)must be the first statement in a constructor. You can use one of them, not both.Ebookpasses the title, author and pages up toBookwithsuper(...), then sets its own field. The parent’s check onpagesprotects the child too.- Throwing
IllegalArgumentExceptionstops a bad object from ever existing. No one can get aBookwith 0 pages. - The fields are
final, so each one must be set exactly once in every constructor path. The compiler checks this for you.
If you write no constructor at all, Java adds an empty one with no parameters. As soon as you write any constructor, that free one disappears. If a child class does not call super(...), Java inserts super() for you, and that fails to compile if the parent has no no-argument constructor.
The Order of Initialisation
A class can contain more than constructors. A static block static { ... } runs once, when the class is first used. An instance block { ... } runs every time an object is made, just before the constructor body. Field initialisers such as int p = log(...) run at the same stage as instance blocks, in the order they are written.
public class Main {
static class Parent {
static { System.out.println("2. Parent static block"); }
int p = log("4. Parent field initialiser");
{ System.out.println("5. Parent instance block"); }
Parent() {
System.out.println("6. Parent constructor");
}
static int log(String s) { System.out.println(s); return 0; }
}
static class Child extends Parent {
static { System.out.println("3. Child static block"); }
int c = log("7. Child field initialiser");
{ System.out.println("8. Child instance block"); }
Child() {
super();
System.out.println("9. Child constructor");
}
}
public static void main(String[] args) {
System.out.println("1. main starts; creating first Child");
new Child();
System.out.println("--- creating second Child (no static blocks this time)");
new Child();
}
}
Output
1. main starts; creating first Child
2. Parent static block
3. Child static block
4. Parent field initialiser
5. Parent instance block
6. Parent constructor
7. Child field initialiser
8. Child instance block
9. Child constructor
--- creating second Child (no static blocks this time)
4. Parent field initialiser
5. Parent instance block
6. Parent constructor
7. Child field initialiser
8. Child instance block
9. Child constructor
mainstarts first. Nested classes are loaded only when the program first needs them.- On the first
new Child(), the parent class is set up, then the child class. Each static block runs once. - Next the parent part of the object is built: its field initialisers and instance blocks, then its constructor body.
- Then the child part is built in the same way.
- The second
new Child()repeats steps 3 and 4 only. Static blocks never run again.
Why does the parent come first? The child’s code may use fields it inherited, so they must already be ready. The very first thing each constructor does, even before its own fields are set, is call the parent constructor.
Common Mistakes
- Copying the same checks into every constructor. Chain to one main constructor with
this(...). - Putting code before
this(...)orsuper(...). It does not compile; the call must come first. - Calling an overridable method from a parent constructor. The child’s version runs before the child’s fields are set, so it sees zeros and nulls.
- Writing a constructor with parameters and then calling
new Book(). The default constructor is gone once you write your own. - Doing slow work in a static block. It runs when the class loads and can hide errors that are hard to trace.
Practice Exercises
Exercise 1. Give a Point class three constructors: Point() for (0, 0), Point(int x) for (x, 0), and Point(int x, int y). Only one should assign the fields.
Show answer
class Point {
final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
Point(int x) { this(x, 0); }
Point() { this(0, 0); }
}
Exercise 2. In the second program, what would print if main created a Parent first and then a Child?
Show answer
The first new Parent() prints lines 2, 4, 5, 6 (Parent static block, then the parent object). The new Child() then prints 3 (Child static block, because Parent is already loaded), followed by 4, 5, 6, 7, 8, 9.
Frequently Asked Questions
Can a Java constructor return a value?
No. A constructor has no return type, not even void. If you write a return type, Java treats it as an ordinary method that happens to share the class name. Use a static factory method if you need to return something special.
When does a static block run in Java?
A static block runs once, when the class is first initialised. That happens the first time you create an object of the class, call one of its static methods, or use one of its static fields that is not a constant.
Summary
- Put the real setup in one constructor; others chain to it with
this(...). super(...)runs the parent constructor and must come first.- Throw an exception in the constructor to stop invalid objects.
- Static blocks run once per class; field initialisers and instance blocks run for every object, before the constructor body.
- The parent part of an object is always built before the child part.
