AI Hints
Home›Java Tutorial›Classes and Objects, Fields and Constructors
Java · Lesson 65 of 120

Fields

The data inside an object.

⏱ 2 min read▶ Video at 1:21:49🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

The variables inside a class are called fields. They are the data each object carries around. A book's title, a person's name, a car's speed.

  • Variables in a class
  • Called fields
  • Each object's data

Fields in Book

Each field has a type and a name, just like a variable. They're declared inside the class, but outside any method. Every object gets its own set. And fields get default values, zero, false, or null.

keyvalue
String titlea field
Declaredin the class body
Each objectits own copy
Defaults0, false, null

Fields and local variables

Fields live as long as their object. Local variables live only while their method runs. Fields get default values. Local variables must be given a value before they're used.

Fields

  • In the class bodyLive with the objectDefault values

Local variables

  • Inside a methodLive during the callMust be set first

Summary

Fields are the variables inside a class. Each object has its own values, which start at defaults. Next, setting them up properly, with a constructor.

Key takeaways
  • Fields = object data
  • Each object its own
  • Defaults: 0, false, null
Next up: Constructors — set up a new object