Fields: Instance Variables in a Class
What you'll learn: How to define instance variables (fields) that hold the unique state of each object created from a class.
What Are Instance Variables?
Instance variables, also called fields, are variables declared inside a class but outside any method. They store the data that belongs to each individual object created from that class. Think of them as the attributes or properties that make each object unique.
Imagine a Dog class as a blueprint. Each dog object needs its own name, age, and breed. These characteristics are stored in instance variables.
Syntax
You declare fields directly inside the class body:
class Dog {
// Instance variables (fields)
String name;
int age;
String breed;
}
Each field has:
- An access modifier (often omitted for now, defaults to package-private)
- A type (primitive or reference)
- A name following variable naming conventions
Each Object Gets Its Own Copy
When you create objects using new, each object gets its own separate copy of all instance variables:
Dog dog1 = new Dog();
dog1.name = "Buddy";
dog1.age = 3;
Dog dog2 = new Dog();
dog2.name = "Max";
dog2.age = 5;
// dog1 and dog2 have independent fields
System.out.println(dog1.name); // "Buddy"
System.out.println(dog2.name); // "Max"
The fields are stored on the heap as part of each object's memory allocation. Changing dog1.age doesn't affect dog2.age.
Default Values
Remember: fields get default initialization values automatically (0 for numbers, false for boolean, null for references).
Key Takeaway: Instance variables (fields) define the state each object carries; every object created from the class gets its own independent copy of all fields.