Field

A field is a variable that belongs to an object. It holds a piece of data that describes the object’s state — its name, its score, its position.

Each object created from a class has its own copy of the fields defined in that class. One Player object might have Name = "Alice" and another might have Name = "Bob" — they share the same class but hold different values.

Fields vs Local Variables#

A local variable lives inside a method and disappears when the method returns. A field lives on the object and persists for as long as the object exists.

  ┌──────────────────────────┐
  │     Player object        │
  │                          │
  │  Name = "Alice"  ← field │
  │  WinCount = 2    ← field │
  │                          │
  │  Greet() {               │
  │    message = "Hi" ← local variable (temporary)
  │  }                       │
  └──────────────────────────┘

How Languages Handle Fields#

The term “field” is most common in C# and Java. Python calls them attributes or instance variables. JavaScript calls them properties. They all refer to the same idea: data stored on an object.

How you declare and access fields varies by language — see the language-specific pages for details.

Common Mistakes#

Confusing fields with local variables A field is declared in the class body, outside any method. A local variable is declared inside a method. If data needs to outlast a single method call, it belongs in a field.

Accessing a field before it’s been set Fields have default values in some languages (C# initialises numeric fields to 0), but relying on defaults without being explicit makes code harder to read. Always initialise fields explicitly — either in the class body or in the constructor.

Exposing fields directly when access control matters Making a field publicly accessible means any code anywhere can change it. In languages like C# this is often handled by using properties instead of raw fields, giving you control over how the value is read and written.

Resources#