🏷 Constructors
4 patterns
Topic: Constructors
All Java patterns related to Constructors — java.evolved
Language
Flexible constructor bodies
Old
class Square extends Shape {
Square(double side) {
super(side, side);
// can't validate BEFORE super!
if (side <= 0)
throw new IAE("bad");
}
}
Modern
class Square extends Shape {
Square(double side) {
if (side <= 0)
throw new IAE("bad");
super(side, side);
}
}
hover to see modern →
JDK 25+
learn more →
Language
Compact canonical constructor
Old
public record Person(String name,
List<String> pets) {
// Full canonical constructor
public Person(String name,
List<String> pets) {
Objects.requireNonNull(name);
this.name = name;
this.pets = List.copyOf(pets);
}
}
Modern
public record Person(String name,
List<String> pets) {
// Compact constructor
public Person {
Objects.requireNonNull(name);
pets = List.copyOf(pets);
}
}
hover to see modern →
JDK 16+
learn more →
Date/Time
Locale constructors to Locale.of()
Old
Locale brazilianPortuguese =
new Locale("pt", "BR");
Modern
Locale brazilianPortuguese =
Locale.of("pt", "BR");
hover to see modern →
JDK 19+
learn more →
Tooling
Class.newInstance() to constructor reflection
Old
Plugin plugin = pluginClass.newInstance();
Modern
Plugin plugin = pluginClass
.getDeclaredConstructor()
.newInstance();
hover to see modern →
JDK 9+
learn more →