2.7.4 Property Getters, Setters, and Backing Fields

Video: Properties (10:42)
Property Getters, Setters, and Backing Fields

Implement a JerseyNumber property over one private integer. This first implementation deliberately has no validation so you can isolate how the accessors execute.

Write the accessors and backing field
Soccer example
public class Player
{
    private int jerseyNumber;

    public int JerseyNumber
    {
        get
        {
            return this.jerseyNumber;
        }

        set
        {
            this.jerseyNumber = value;
        }
    }
}

The field stores the number. The property declaration gives its public name and type. A getter returns an int. In the setter, value is the implicit input supplied by the assignment, with the property type int. Do not declare a separate parameter named value.

Translate assignments into accessor work
Caller method
Player jordan = new Player();
jordan.JerseyNumber = 7;
int displayedNumber = jordan.JerseyNumber;
Execution order
Moment Backing field Action
After creation 0 Default integer initialization
After assignment 7 Setter receives value 7 and stores it
After read 7 Getter returns 7; caller stores the result

Reading the property does not run its setter. Assigning the property does not directly write the private field from the caller; it executes the setter body.

Use the field inside these accessors

This implementation still accepts -5. A property is a location for access logic, not automatic validation.

Apply the idea
Check your understanding