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
- Chain constructors using
this()
and verify initialization happens once. - Create an immutable class with all fields
final
and initialize via constructor.