Fields and the constructor

An object is assembled once, not patched from the outside.

A class describes fields and methods. new User("Ann") allocates an object and immediately calls the constructor. The constructor is named after the class and has no return type. Its job is to assemble the object in a usable state. An empty constructor plus a scatter of setters outside leaves a moment when the name is still null while code is already calling methods.

A field without initialization gets a default value: null for a reference, 0 for a number. That is not "empty by meaning", it is a technical zero. If a user must have a name, the constructor should require it. A check in the constructor is cheaper than a check in every method.

A reference variable holds a reference. User a = b does not copy the person: both variables look at one object. A field changed through a is visible through b. Copying is a separate decision: a copy constructor or immutable fields.

In this lesson the program prints a name. You can declare the class next to main in the same file as long as it is not public. The check runs Main and reads one line of output.

Practice

  1. The constructor's name

    What is the constructor of the class User called?

    • create
    • User
    • main
    • new
  2. The field's value

    A String reference field was never assigned. What does it hold right after new if the constructor did not touch it?

  3. Print the name

    Build an object with the name Ann and print that name on one line.