Fields

A field is a variable that’s defined in the body of a class, outside any of the class’s methods. Fields, which are also called class variables, are available to all the methods of a class. In addition, if the field specifies the public keyword, the field is visible outside the class. If you don’t want the field to be visible outside the class, use the private keyword instead.

A field is defined the same as any other Java variable, but it can have a modifier that specifies whether the field is public or private. Here are some examples of public field declarations:

public int trajectory = 0;

public String name;

public Player player;

To create a private field, specify private instead of public:

private int x_position = 0;

private int y_position = 0;

private String error-message = “”;

Fields can also be declared as final:

public final int MAX_SCORE = 1000;

The value of a final field can’t be changed after it has been initialized. Note: Using capital letters in final field names is customary (but not required).

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.