Comp 110 Fields

Field

An field (sometimes called an instance variable) models a property that all instances of a class have. It is defined in the class, and can be called in any method within the class.

class Person {

    // Fields
    private int _height;
    private double _weight;
    private String _name;
    private String _gender;

    // Constructor
    public Person(String name, String gender, double height, double weight) {
        _name = name;
        _gender = gender;
        _height = height;
        _weight = weight;
    }

    // Methods
    public String talk() {
        return "My name is " + _name + " and I am a " + _gender;
    }

}

For example, the above images shows a screenshot of a Person class. _height_weight_name, and _gender are all the fields of this Person class. Height, weight, name, and gender are all qualities that all "real life" person has, so we made _height_weight_name, and _gender fields, or qualities all instances of the person class have.

In different instances of a class, fields will hold different values. For example:

Let's say we created two instances of the Person class. One of these Person objects will be named "Kris", so its _name field will be equal to "Kris". The other Person object that we create will be named "Cam", so its _name field will be equal to "Cam". Although both Kris and Cam are both Person objects, they have different values for their _name field.

Fields are declared within a class, but not within a single method, and are able to be accessed from anywhere in the class. In the above image, you can see that we are declaring the fields of the Person class within the class, but not within the methods or constructors of the Person class. If we declare a variable within a method or constructor it is a local variable and not an field.

Fields and local variables can both store the same thing (either a primitive such as an int, or a reference to an instance of some other class (an object)), but the difference is that fields can be accessed within any other method of that class, whereas local variables cannot. In the above image, if we look at the talk() method we can see that both the _name and _gender fields are being accessed. This works because _name and _gender are fields. If we attempted to access the name and gender variables (note the lack of _) in the Person constructor from the talk() class, we would not be able to because the name and gender variables in the Person constructor are local variables and not fields. 

In this course we will always be starting an field's name with an underscore ('_'). This will help us more easily differentiate between fields and local variables.