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

Field Initialization: Declaration vs Constructor

Understand the difference between initializing fields at declaration and initializing them in constructors.

Field Initialization: Declaration vs Constructor

What you'll learn: The two places you can initialize class fields and when to use each approach.


When creating a class, you have two options for giving fields their starting values: you can initialize them directly when declaring the field, or you can initialize them inside a constructor.

Initialization at Declaration

You can assign a value right where you declare the field:

public class Circle {
    private double radius = 1.0;  // initialized at declaration
    private String color = "red"; // initialized at declaration
}

This approach works well for simple, fixed default values that every object should have. The value is set before any constructor runs.

Initialization in Constructor

Alternatively, you can leave fields uninitialized at declaration and set them in the constructor:

public class Circle {
    private double radius;
    private String color;
    
    public Circle() {
        radius = 1.0;  // initialized in constructor
        color = "red"; // initialized in constructor
    }
}

When to Use Each

Declaration initialization is best when:

  • The default value is simple and never changes
  • You want the same default for all constructors

Constructor initialization is best when:

  • You need to accept parameters
  • The initial value requires computation or logic
  • Different constructors need different defaults

Combined Approach

You can mix both approaches:

public class Circle {
    private double radius = 1.0;  // default at declaration
    
    public Circle(double r) {
        radius = r;  // constructor overrides the default
    }
}

If you initialize at declaration and in the constructor, the constructor value wins—it runs second and overwrites the declaration value.

Key Takeaway: Fields can be initialized at declaration for simple defaults or in constructors for parameter-driven or computed values; constructor initialization always happens after declaration initialization.