Fields

index
BASIC

Each object typically has its own data, stored in the variables, or fields, of that object. A field is a variable belonging to a particular object.

Here are some examples:

class Person {
    String name;    // this is a field
    int age;        // this is another field
    Person spouse;  // and yet another
    static String species = "homo sapiens"; // a static field
    static long population = 600000000;     // another static field
    ...
}

Every Person object we make will have its own name, age, and spouse variables, and their values are typically different from those in other Person objects. If we make 16 Person objects, there will be 16 name variables, each having an independent value.

If a field is static, however, there is only one of it, regardless of how many objects we create. A static field is held in common by all objects of that class. In the above example, while each individual Person object is a member of the species homo sapiens, it is also true that every Person is a homo sapiens. If we were to change the value of species, we would be changing it for everybody at once.

The static variable population works the same way--there is only one of it. However, we think of it as applying to the class as a whole (there are about six billion persons in the world), rather than to the individual objects of the class.

Every variable also has a scope, which is the part of the program in which the variable may be used. The scope of a field is the entire class in which it is declared, no matter where in the class the field is declared. (But it is conventional to declare all the fields before any methods.