Constructors in Java β <code>this</code>, <code>super</code>, Overloading
A constructor is a special method that runs when you new an object. It has the same name as the class, no return type (not even void), and its job is to initialise the new instance.
Basic shape
public class User {
private final String name;
private final int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
}
var u = new User("Alice", 30);
The default constructor
If you declare no constructor, Java provides a public no-arg one. The moment you declare any constructor, the default disappears:
public class Foo {
public Foo(int x) { ... }
}
new Foo(); // β compile error β no no-arg constructor
Overloading and this(...)
public class Rectangle {
private final int w, h;
public Rectangle(int w, int h) {
this.w = w;
this.h = h;
}
public Rectangle(int side) {
this(side, side); // delegate β avoids duplicating validation
}
}
this(...) must be the first statement of a constructor. You can't call this() twice.
super(...) β the parent constructor
public class Admin extends User {
private final List<String> roles;
public Admin(String name, int age, List<String> roles) {
super(name, age); // call parent
this.roles = List.copyOf(roles);
}
}
If you don't write super(...), the compiler inserts an implicit super(). If the parent has no no-arg constructor, you must call super(...) explicitly.
Private constructor β singletons and utility classes
public final class MathUtils {
private MathUtils() {} // prevent instantiation
public static int square(int n) { return n * n; }
}
public enum Config {
INSTANCE; // singleton via enum
private final Properties props = load();
}
Initialisation order
- Static fields and static initialisers β once, when the class is loaded.
new ClassName(...)allocates memory and zeroes fields.- Parent constructor (explicit or implicit
super(...)). - Instance field initialisers and instance initialiser blocks.
- This constructor's body.
Common mistakes
- Forgetting to initialise
finalfields β compile error ("variable might not have been initialized"). - Calling overridable methods from a constructor β subclass override runs before the subclass is fully initialised.
- Throwing exceptions during partial construction β half-built objects can escape if the constructor stores
thissomewhere before completing. - Using
this()withsuper()β only one is allowed, and only as the first statement.