Link Search Menu Expand Document

Objects

Table of Contents

  1. Fields
  2. Constructor

Fields

The current state of your object is stored in its fields. Because of this, the fields of your objects must always be declared private. This ensures that no client of your object will be able to directly change the state of your object in a way that you haven't allowed them to.

Constructor

A line of code where you are creating a variable, like int num = 1, is doing 2 things. It declares a variable num and then sets the value of num to 1. These two steps are the variable declaration and initialization:

int num; // declaration
num = 1; // initialization

Normally, we combine these into one line of code, but fields must exist in the scope of the entire class but must also be initialized in the constructor. For that reason, we put all the field declarations at the top of the program underneath the class header, and all field initializations should be done in the constructor.

public class SomeClass {
    private int someField;

    public SomeClass() {
        someField = 1;
    }
}