Multiple Instances: Each Object Has Its Own State
What you'll learn: You'll understand that each object created from the same class maintains its own independent copy of instance fields.
The Core Idea
When you create multiple objects from the same class using new, each object gets its own separate set of instance variables. Think of a class as a cookie cutter and objects as the individual cookies—they share the same shape (the class blueprint), but each cookie is distinct and can be decorated differently.
Changing a field in one object does not affect the same field in another object, even though they come from the same class. Each object lives independently in memory with its own state.
A Simple Example
class BankAccount {
String owner;
double balance;
BankAccount(String owner, double balance) {
this.owner = owner;
this.balance = balance;
}
}
// Creating multiple instances
BankAccount account1 = new BankAccount("Alice", 1000.0);
BankAccount account2 = new BankAccount("Bob", 500.0);
// Each object has its own state
// account1.balance is 1000.0
// account2.balance is 500.0
Here, account1 and account2 are completely separate objects. Changing account1.balance won't touch account2.balance. Each BankAccount object maintains its own owner name and balance value.
Why This Matters
This independence is fundamental to object-oriented programming. It allows you to model real-world entities where each instance represents a distinct thing with its own properties—like multiple bank accounts, cars, or users in a system.
Key Takeaway: Each object created from a class has its own independent copy of all instance fields; modifying one object's state does not affect any other object's state.