Java Object Construction: Overloading, Default Fields, this(), and Initialization Blocks
Every way to initialize Java objects: overloading and signatures, default field values, no-argument constructors, field initializers, parameter naming with this, calling this(...), initialization blocks, static initializers, construction order and cleanup without destructors.
kvi5hnuCode Sprout team member13 min readOn this page
Getting an object into a valid state is important enough that Java offers several tools for it: multiple constructors, default values, initializers on field declarations, constructors that delegate to each other, and initialization blocks. Below you'll see each one, the precise order in which they run, and finally what happens when an object is no longer needed.
Overloading
A class may offer several constructors. StringBuilder, for instance, can start empty, start with some text, or start with a chosen capacity:
var log = new StringBuilder();
var receipt = new StringBuilder("Order #4471\n");
var big = new StringBuilder(512);
Several methods sharing a name but differing in their parameter lists is called overloading. For each call, the compiler compares the argument types with every candidate's parameter types and picks the most specific fit. This step is overload resolution; it fails with a compile error when no candidate fits, or when two fit equally well.
You can overload any method, not only constructors. To describe a method completely, you need its name and its parameter types: its signature. For example, String has six public indexOf methods:
indexOf(int)
indexOf(int, int)
indexOf(int, int, int)
indexOf(String)
indexOf(String, int)
indexOf(String, int, int)
The return type isn't part of the signature. You can't have two methods with the same name and parameter types that differ only in return type:
class Ret {
int f() { return 1; }
double f() { return 1; } // error: method f() is already defined in class Ret
}
How overload resolution picks a method
When the argument types don't match exactly, the compiler applies conversions in phases:
- First it looks for methods applicable with widening primitive conversions only (
int→long→float→double,char→int), choosing the most specific one. - Only if none applies does it consider boxing/unboxing (
int↔Integer). - Only if still none applies does it consider varargs methods (
int..., covered in the inheritance part).
public class Solution {
static void show(int x) { System.out.println("int " + x); }
static void show(long x) { System.out.println("long " + x); }
static void show(double x) { System.out.println("double " + x); }
static void show(Integer x) { System.out.println("Integer " + x); }
static void show(Object x) { System.out.println("Object " + x); }
static void show(int... xs) { System.out.println("varargs " + xs.length); }
public static void main(String[] args) {
show(5);
show(5L);
show(5.0f);
show('A');
show((short) 3);
show(Integer.valueOf(7));
show("s");
show();
show(1, 2);
StringBuilder b = new StringBuilder('\n');
System.out.println("[" + b + "] length=" + b.length() + " capacity=" + b.capacity());
}
}
int 5
long 5
double 5.0
int 65
int 3
Integer 7
Object s
varargs 0
varargs 2
[] length=0 capacity=10
Notice show('A'): a char widens to int, so it prints int 65, not a character.
If two candidates are equally good, the call is ambiguous and won't compile:
static void f(int a, double b) { }
static void f(double a, int b) { }
f(1, 2); // error: reference to f is ambiguous
Default Field Initialization
If a constructor doesn't set a field, the field gets its default value automatically: numbers become 0, boolean becomes false, and object references become null.
This is an important difference between fields and local variables. Local variables must always be explicitly initialized before use; fields are initialized automatically.
Relying on defaults is often considered poor practice. It makes code harder to understand, because initialization happens invisibly, and it easily leaves references null. If an Employee constructor forgot to set startDate, then:
LocalDate h = omar.getStartDate();
int year = h.getYear(); // throws NullPointerException: h is null
The No-Argument Constructor
Many classes have a no-argument constructor that creates an object with sensible default state:
public Employee() {
name = "";
salary = 0;
startDate = LocalDate.now();
}
If a class has no constructors at all, Java supplies a default constructor for you. It takes no arguments and leaves every field at its default value (0, false, null).
But if you write even one constructor, you no longer get the free one. The original Employee class had only Employee(String n, double s, int year, int month, int day), so:
e = new Employee(); // error: constructor Employee in class Employee cannot be applied to given types
Explicit Field Initialization
Whatever constructor is called, every field should end up with a meaningful value. Overloaded constructors give you many ways to set initial state, but you can also assign a value in the field declaration:
class Employee {
private String name = "";
...
}
This assignment is carried out before the constructor body runs. It's especially useful when all constructors should set a field to the same value.
The initial value doesn't have to be a constant. It can be any expression, including a method call:
class Employee {
private static int nextBadge;
private int badge = takeBadge();
...
private static int takeBadge() {
int r = nextBadge;
nextBadge++;
return r;
}
}
Parameter Names
Trivial constructors need parameter names, and it's tempting to use single letters:
public Employee(String n, double s) {
name = n;
salary = s;
}
That saves typing but costs readability: n and s say nothing until you read the body. Spelling the names out with some prefix or suffix fixes that, at the price of a little noise:
public Employee(String initialName, double initialSalary) {
name = initialName;
salary = initialSalary;
}
The most common Java idiom gives parameters the same names as the fields. The parameter shadows the field, so salary means the parameter, but you can still reach the field as this.salary. Recall that this is the implicit parameter: the object being constructed.
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
IDEs generate constructors in exactly this style. Forgetting the this. (writing name = name;) is a classic bug: it assigns the parameter to itself and leaves the field unset. IDEs warn about such self-assignments.
Calling Another Constructor with this(...)
The keyword this has a second meaning. If the first statement of a constructor has the form this(...), the constructor calls another constructor of the same class:
public Employee(double s) {
// calls Employee(String, double)
this("Temp-" + nextBadge, s);
nextBadge++;
}
new Employee(47000) runs Employee(double), which first runs Employee(String, double) and then continues with its own remaining statements. This lets you write common construction code once, typically in the most complete constructor, with the other constructors delegating to it.
Java 25: statements before this(...) and super(...)
Traditionally, this(...) had to be the very first statement, so you couldn't validate or prepare arguments before delegating. Java 25 finalized "flexible constructor bodies" (JEP 513): a constructor may now run statements before this(...) (or super(...)), as long as they don't use the object under construction (no reading its fields or calling its instance methods):
public Employee(double s) {
if (s < 0) throw new IllegalArgumentException("Negative salary: " + s); // allowed in Java 25
this("Anonymous", s);
}
On Java 21 you'd validate inside a static helper method called in the argument list instead. (Java 22–24 had this feature as a preview.)
Initialization Blocks
You've seen two ways to initialize instance fields: in a constructor, and in the field declaration. There's a third: an initialization block. A class can contain plain blocks of code, which run every time an object is constructed:
class Employee {
private static int nextBadge;
private int badge;
private String name;
private double salary;
// object initialization block
{
badge = nextBadge;
nextBadge++;
}
public Employee(String n, double s) {
name = n;
salary = s;
}
public Employee() {
name = "";
salary = 0;
}
...
}
The block sets badge regardless of which constructor is used. The initialization block runs first, then the constructor body.
Initialization blocks are never necessary and not common. Putting the code in a constructor (and using this(...) to share it) is usually clearer. Their main real-world use is in anonymous classes, which can't declare constructors (covered in the inner classes article).
The Construction Order
With so many mechanisms, what exactly happens when a constructor is called?

- If the first statement of the constructor calls another constructor (
this(...)), that constructor runs with the provided arguments, then the rest of this body. - Otherwise:
- All instance fields are set to their default values (
0,false,null). - All field initializers and initialization blocks run, in the order they appear in the class.
- The constructor body runs.
- All instance fields are set to their default values (
(With inheritance, a call to the superclass constructor joins the process; the inheritance part covers that.)
If understanding a class requires knowing these steps by heart, it is too clever. In particular, avoid initializers that depend on the textual order of field declarations; reordering fields during a refactor shouldn't change behavior.
Static Initialization
To initialize a static field, give it an initial value:
private static int nextBadge = 1;
or, if it needs more complex code, use a static initialization block, marked with static:
private static final RandomGenerator generator = RandomGenerator.getDefault();
// static initialization block
static {
nextBadge = 5000 + generator.nextInt(1000); // first badge somewhere in 5000..5999
}
Static initialization happens once, when the class is initialized, which is the first time it's actually used: an instance is created, a static method is called, or a static field that isn't a compile-time constant is accessed. (Loading the class file and initializing the class are separate steps; a class can be loaded without being initialized.) Like instance fields, static fields are 0, false or null unless set otherwise, and static initializers and static blocks run in the order they appear.
Better random numbers: RandomGenerator
The example uses java.util.random.RandomGenerator (Java 17), which provides modern random-number algorithms with different trade-offs. RandomGenerator.getDefault() is a good choice for most purposes; RandomGenerator.of("L64X128MixRandom") selects a specific algorithm (the package documentation explains the choices). Call generator.nextInt(n), nextDouble(), and so on.
The original java.util.Random (from Java 1.0) is a 48-bit linear congruential generator, so its sequence repeats after 2⁴⁸ values and has known statistical weaknesses. For simulations that draw many millions of values that matters; the newer algorithms behind RandomGenerator have far longer periods and better quality. Prefer RandomGenerator in new code. For legacy code that requires a Random, wrap a better algorithm with Random.from(RandomGenerator.getDefault()) (Java 19).
Putting It All Together
This program demonstrates overloaded constructors, this(...), a no-argument constructor, a field initializer, an object initialization block and a static initialization block:
public class Solution {
public static void main(String[] args) {
var staff = new Employee[3];
staff[0] = new Employee("Omar", 52000);
staff[1] = new Employee(47000);
staff[2] = new Employee();
for (Employee e : staff) {
System.out.println("name=" + e.getName() + ",badge=" + e.getBadge() + ",salary=" + e.getSalary());
}
}
}
class Employee {
private static int nextBadge;
private int badge;
private String name = ""; // instance field initialization
private double salary;
// static initialization block
static {
// complex setup could go here (reading configuration, computing tables, ...)
nextBadge = 1000;
}
// object initialization block
{
badge = nextBadge;
nextBadge++;
}
// three overloaded constructors
public Employee(String n, double s) {
name = n;
salary = s;
}
public Employee(double s) {
// calls the Employee(String, double) constructor
this("Temp-" + nextBadge, s);
}
// the no-argument constructor
public Employee() {
// name initialized to "" -- see above
// salary not explicitly set -- initialized to 0
// badge initialized in initialization block
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public int getBadge() {
return badge;
}
}
name=Omar,badge=1000,salary=52000.0
name=Temp-1001,badge=1001,salary=47000.0
name=,badge=1002,salary=0.0
Trace the second employee: the argument "Temp-" + nextBadge is evaluated before the delegated constructor runs, while nextBadge is 1001. Then Employee(String, double) runs the initialization block (badge = 1001, nextBadge becomes 1002) and its body.
Object Destruction: No Destructors
Some languages, notably C++, have destructors: methods that run when an object is destroyed, mainly to free its memory. Java has automatic garbage collection, so memory is reclaimed for you, and Java has no destructors.
But some objects hold resources other than memory: open files, network connections, database handles. Those should be released as soon as you're done with them.
- If a resource must be released promptly, give the class a
closemethod and call it when you're done. Thetry-with-resources statement (which you've seen with files, and which the exceptions part explains) callscloseautomatically. Classes do this by implementingAutoCloseable. - If cleanup can wait until the JVM exits, register a shutdown hook with
Runtime.getRuntime().addShutdownHook(...). java.lang.ref.Cleanercan register an action that runs some time after an object becomes unreachable. It's a safety net for rare cases, not a replacement forclose.
Common questions
Why can't I overload methods by return type?
At a call site such as compute(5);, the result may be ignored, so the compiler would have no way to tell which method you meant. That's why the signature is only the name plus the parameter types.
Does this(...) still have to be the first statement?
Since Java 25, no. Flexible constructor bodies (JEP 513) allow statements before this(...) or super(...), for example to validate arguments, as long as they don't use the object under construction. On Java 21 and earlier, this(...) must be first.
What runs first: field initializers or the constructor body? Field initializers and instance initialization blocks run first, in source order, and then the constructor body runs. With inheritance, the superclass constructor runs before any of the subclass's field initializers.
Is finalize gone?
It is deprecated for removal (since Java 18), and finalization can already be disabled with --finalization=disabled. Don't write finalize methods. Use AutoCloseable with try-with-resources for prompt cleanup, and use Cleaner only as a last-resort safety net.
How many constructors should a class have? As few as make construction convenient. When a class needs many optional parameters, chains of constructors get hard to read. Consider static factory methods with descriptive names or a builder object instead.
Summary
- Overloading: several methods (or constructors) with the same name and different parameter lists. A method's signature is its name plus parameter types; the return type isn't part of it.
- Overload resolution prefers exact or widening matches, then boxing, then varargs. Ambiguous calls don't compile. Beware traps like
new StringBuilder('\n'). - Fields get defaults (
0,false,null); local variables don't. Don't rely on defaults for object references. - A free no-argument constructor exists only if you write no constructors.
- Initialize fields in declarations (
private String name = "";), in constructors, or (rarely) in initialization blocks. - Name constructor parameters like fields and assign with
this.name = name;. Usethis(...)to delegate to another constructor. Java 25 allows validation statements before it. - Order: defaults → field initializers and blocks in source order → constructor body. Static initialization runs once, when the class is first used (initialized).
- Java has no destructors: release resources with
closeand try-with-resources. Never usefinalize.
Practice Questions
Can a class have both void print(int x) and int print(int y)? Why?
No. Both have the signature print(int); parameter names and return types aren't part of the signature, so the compiler reports that the method is already defined.
A class declares only public Point(double x, double y). Does new Point() compile?
No. Once a class declares any constructor, Java no longer provides the default no-argument constructor. Add public Point() { this(0, 0); } if you need it.
What's wrong with this constructor? public Employee(String name) { name = name; }
name = name; assigns the parameter to itself; the field is never set and stays null. Write this.name = name;.
Which overload does show(10) call if only show(long) and show(Integer) exist?
show(long). Widening int → long is considered in the first phase, before boxing to Integer.
In what order do these run for new A(): a field initializer int x = f();, an instance block { g(); }, and the constructor body, if the block is written before the field?
Field initializers and instance blocks run in source order, so the block g() runs first, then x = f(), then the constructor body.
Why should you not rely on finalize to close a file?
There's no guarantee when or whether finalize runs, so the file could stay open indefinitely (and you might run out of file handles). finalize is also deprecated for removal. Provide a close method and use try-with-resources.
Previous: Java Method Parameters: Pass by Value Explained
Next: Java Records: Compact Data Classes with Canonical and Compact Constructors
Related reading
- Java Block Scope and if/else Statements
- The Java String API, Code Points, StringBuilder and Text Blocks
- Java Long-Running Tasks in User Interfaces: Swing Worker Threads and Callbacks
- Java CompletableFuture: Asynchronous Programming with Callbacks and Composition
- Java ConcurrentHashMap, CopyOnWriteArrayList and Parallel Array Algorithms

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.