The Relationship Between Fields and Methods
What you'll learn: You'll discover how methods bring fields to life by reading and modifying them to create meaningful object behavior.
The Core Idea
Fields store an object's state (its data), while methods define its behavior (what it can do). The magic happens when methods interact with fields: they read field values to make decisions, and change field values to update the object's state. This relationship is what makes objects useful — they're not just data containers, they're active entities that can do things with their data.
Think of a simple BankAccount class:
class BankAccount {
double balance; // Field: stores state
// Method: uses and modifies the field
void deposit(double amount) {
balance = balance + amount; // Reading and writing the field
}
// Method: reads the field
double getBalance() {
return balance; // Returning the field's value
}
}
Here, balance is just a number sitting in memory. The deposit method brings it to life by reading its current value, adding to it, and storing the new result back. The getBalance method lets the outside world see what's stored in that field.
Why This Matters
Without methods accessing fields, your objects would be useless — just data with no way to interact with it. Methods provide controlled access to fields, allowing you to implement business rules (like "don't allow negative deposits") and keep your object's state consistent.
Every method in a class automatically has access to all fields of that class. When you write balance inside a method, Java knows you mean "this object's balance field."
Key Takeaway: Methods bring fields to life by reading and modifying them; this relationship between stored state (fields) and behavior (methods) is the foundation of object-oriented programming.