Course contentsShow
← Java
Lesson 72 of 2,8702. Variables and Primitive TypesFree lesson

Blank Finals in Constructors

Declaring final instance variables without immediate initialization and assigning them in constructors.

Blank Finals in Constructors

What you'll learn: How to declare a final variable without an immediate value and assign it later in a constructor.

The Core Idea

You've learned that final variables must be initialized and can never change. But here's a flexible twist: you don't have to assign the value right when you declare the variable. You can declare a final instance variable "blank" (without a value) and then assign it inside a constructor. This is called a blank final.

The rule is simple: the final variable must receive its value by the time the constructor finishes running. After that, it's locked forever.

Why This Matters

Think of it like personalizing a keychain. The keychain (your object) can have a custom engraved name (the final variable). You don't engrave it at the factory (declaration time)—you engrave it when someone orders it (construction time). Once engraved, it never changes.

This lets different objects of the same class have different final values, which is incredibly useful.

Example in Code

public class Person {
    final int birthYear;  // blank final - declared but not initialized

    public Person(int year) {
        birthYear = year;  // must assign in constructor
    }
}

Each Person object can have its own unique birthYear that never changes after construction.

Important Rules

  • The blank final must be assigned in every constructor
  • You can only assign it once
  • If you forget to assign it, you'll get a compilation error

Key Takeaway: A blank final is a final variable declared without an initial value, which must be assigned exactly once in the constructor before the object is fully created.