unkletayo
8

Classes: fields, constructors, and defaults

What a class declaration contains, where default values come from, and what constructors actually do.

Adetayo Akinsanya2026-07-216 min read

  • Java
  • Core Java
  • OOP
  • Classes
  • Constructors

Part 8 of the series.Read Strings: building, joining, and formatting (Part 7) first if you have not.

In this article (7 sections)
  1. What a class declaration contains
  2. Fields and their default values
  3. Constructors
  4. The default constructor
  5. Constructor overloading
  6. Establishing invariants
  7. Prediction exercise
public class Counter {
    int count;
    boolean active;
    String label;
}

Counter c = new Counter();
System.out.println(c.count);   // 0
System.out.println(c.active);  // false
System.out.println(c.label);   // null

We never set those fields. Where did 0, false, and null come from?

What a class declaration contains

A class declaration describes a template for objects. Each object created from that template gets its own copy of the instance state the class declares.

A class body can contain four kinds of members:

Fields describe the state an object holds. int count says every Counter object has a slot named count that holds an int.

Constructors run when a new object is created. Their job is to put the object into a valid initial state.

Methods define the operations the object supports.

Nested types, inner classes, static nested classes, and so on, are covered in a later article.

Fields and constructors are the focus here.

Fields and their default values

A field declaration gives each instance a named slot to hold a value. The type determines what values are allowed and how much space the slot occupies.

public class Account {
    String id;          // reference to a String
    int balance;        // 32-bit integer
    boolean active;     // true or false
    double rate;        // 64-bit floating-point
}

Before a constructor runs, the JVM allocates memory for the new object and sets each field to its default value. The JLS (§4.12.5) defines defaults for every type:

Type Default value
byte, short, int, long 0
float 0.0f
double 0.0d
char '\u0000' (the null character)
boolean false
Any reference type null

This is why c.count was 0 and c.label was null in the opening example. The JVM set them before any constructor ran.

Default values exist so that every field has a defined value from the moment the object is allocated. Code that reads a field can always rely on getting a value, not uninitialized memory.

You can supply an explicit initial value directly in the declaration:

public class Account {
    String id;
    int balance = 0;         // explicit, matches the default
    boolean active = true;   // different from the default
    double rate = 0.05;
}

Field initializers like active = true run after the JVM’s default-value pass and before the constructor body. Initialization order covers the full sequence, including static initializers and instance initializer blocks.

Constructors

A constructor is a block of code that runs when new creates an object. It looks like a method but has no return type and must be named after the class.

public class Account {
    String id;
    int balance;
    boolean active;

    Account(String id, int balance) {
        this.id = id;
        this.balance = balance;
        this.active = true;
    }
}

this.id refers to the field. id without this refers to the parameter. When a parameter name shadows a field name, this distinguishes them.

What makes a constructor different from a method? A constructor runs exactly once per object, at creation time, and receives the newly allocated object as this. The constructor’s job is to put that object into a valid state before any method can be called on it.

An Account with a negative balance or a null ID might violate invariants that the rest of the code depends on. The constructor is the right place to enforce those constraints:

Account(String id, int initialBalance) {
    if (id == null || id.isEmpty()) throw new IllegalArgumentException("id required");
    if (initialBalance < 0) throw new IllegalArgumentException("balance cannot be negative");
    this.id = id;
    this.balance = initialBalance;
    this.active = true;
}

If the constructor throws, the new expression throws and no object is returned. The partially constructed object is not reachable from the caller’s perspective.

The default constructor

If a class has no declared constructor, the Java compiler generates a default constructor: a public no-argument constructor that calls super() and does nothing else.

// source code
public class Counter {
    int count;
}

// what the compiler generates (not visible in source)
public Counter() {
    super();
}

The moment you declare any constructor, the compiler stops generating the default. If you declare a one-argument constructor and also want a no-argument constructor, you must write both explicitly.

public class Account {
    String id;
    int balance;

    Account(String id, int balance) {
        this.id = id;
        this.balance = balance;
    }

    // no default constructor generated — Account() { } would be a compile error
}

Account a = new Account();  // compile error: no suitable constructor found

This is a common source of confusion when adding a first constructor to an existing class: callers that relied on the default constructor break.

Constructor overloading

A class can have multiple constructors, as long as their parameter lists differ in type, number, or order. The compiler picks the matching constructor based on the argument types at the call site.

public class Account {
    String id;
    int balance;
    boolean active;

    Account(String id) {
        this.id = id;
        this.balance = 0;
        this.active = true;
    }

    Account(String id, int initialBalance) {
        this.id = id;
        this.balance = initialBalance;
        this.active = true;
    }
}

Both constructors work, but they repeat the assignment this.active = true. When constructors share setup logic, this(...) delegates to another constructor in the same class:

Account(String id) {
    this(id, 0);        // delegates to Account(String, int)
}

Account(String id, int initialBalance) {
    if (id == null || id.isEmpty()) throw new IllegalArgumentException("id required");
    if (initialBalance < 0) throw new IllegalArgumentException("balance cannot be negative");
    this.id = id;
    this.balance = initialBalance;
    this.active = true;
}

this(id, 0) must be the first statement in the constructor. Only one constructor does the real work; the others delegate to it. Initialization order covers what happens step by step when this() and super() chain together.

Establishing invariants

An invariant is a condition that must hold for all objects of a class. For Account, the invariants might be: id is never null, balance is never negative, active is always set to something meaningful.

The constructor is the only place where you can guarantee an invariant holds from the moment an object exists. Once an object escapes the constructor, callers can invoke any public method, so the invariants need to be maintained by those methods too, but they start from a valid state if the constructor did its job.

Separating valid-state enforcement (constructor) from operation logic (methods) keeps each piece of code focused.

Prediction exercise

public class Sensor {
    String location;
    double reading = -1.0;
    boolean calibrated;

    Sensor(String location) {
        this.location = location;
        this.calibrated = true;
    }
}

Sensor s = new Sensor("room-1");

What are the values of s.location, s.reading, and s.calibrated after construction? If you remove the constructor and call new Sensor() instead, what are the three field values?

Questions or corrections

Found a mistake or have a question about this breakdown? Reach out directly.

Reply on X (@unkletayor)Email feedback