Java - Constructors

Constructors

class Person {
  private final String name; private int age;
  Person() { this("Unknown", 0); }     // default constructor
  Person(String name, int age) {         // overloaded
    this.name = name; this.age = age;
  }
}

If you declare any constructor, Java does not provide a no-arg default automatically.

Try it

  1. Chain constructors using this() and verify initialization happens once.
  2. Create an immutable class with all fields final and initialize via constructor.