Course contentsShow
← Java
Lesson 357 of 2,8708. Classes and EncapsulationFree lesson

Common Pitfalls: Referring to Uninitialized Fields

Learn about forward reference restrictions and why you cannot use fields before they are declared in initializers.

Common Pitfalls: Referring to Uninitialized Fields

What you'll learn: You'll discover why Java restricts you from using a field before it's been declared, even though fields get default values automatically.

The Forward Reference Problem

You know that uninitialized fields automatically receive default values (0, false, null, etc.). So why can't you reference them before they're declared in your code? Java enforces a "forward reference restriction" to prevent confusing and error-prone code.

The rule: You cannot use a field in an initializer before the field's declaration appears in the class.

Think of it like reading a book: you can't reference Chapter 5 if you're still on page 10 and Chapter 5 starts on page 100. Java reads your class top-to-bottom, and you must declare something before using it in initialization logic.

Where This Trips You Up

public class Account {
    private double balance = calculateInitial(); // ❌ Error!
    private double startingAmount = 1000.0;
    
    private double calculateInitial() {
        return startingAmount; // startingAmount not yet declared!
    }
}

This fails because balance tries to use startingAmount before startingAmount is declared. Swap the order and it works:

public class Account {
    private double startingAmount = 1000.0; // ✓ Declared first
    private double balance = calculateInitial(); // ✓ Now safe
    
    private double calculateInitial() {
        return startingAmount;
    }
}

Why Java Enforces This

Even though startingAmount would get the default value 0.0, letting you reference it early creates confusing code where declaration order silently changes behavior. Java forces you to be explicit and clear about dependencies.

Key Takeaway: Fields must be declared before they are referenced in field initializers or instance initializer blocks—declaration order matters for initialization dependencies.