[!NOTE] A class isn't just a container for data. It actively manages its own internal State, protecting its variables from invalid manipulation.
Class Attributes
Class Attributes (often called Fields or Instance Variables) are variables declared directly inside the class block, but outside of any specific method.
Unlike local variables inside a method, which are destroyed the moment the method finishes, Instance Variables stay alive as long as the Object itself stays alive in memory.
public class Player {
// These are Instance Variables. Every new Player object gets its own copy!
String username;
int health = 100; // Default starting value
boolean isAlive = true;
// A method that alters the Object's internal state
public void takeDamage(int damage) {
health = health - damage;
System.out.println(username + " took damage! Health is now " + health);
if (health <= 0) {
isAlive = false;
System.out.println(username + " has died.");
}
}
}
Modifying Multiple Instances
Because every object instantiated with new gets its own completely isolated copy of the instance variables, changing one object has absolutely zero effect on another.
public class Game {
public static void main(String[] args) {
Player p1 = new Player();
p1.username = "HeroGuy";
Player p2 = new Player();
p2.username = "VillainBoss";
// P2 attacks P1!
p1.takeDamage(40);
// Output proves isolation!
System.out.println(p1.health); // Outputs 60
System.out.println(p2.health); // Output 100 (Unaffected!)
}
}
The 'static' Keyword Exception
What if you want all objects to share the exact same variable? For example, what if you want to track the total number of players currently connected to the server?
If you add the static keyword to a variable, it detaches from the individual objects and attaches to the Class itself. There is now only one copy of that variable in the entire application memory, shared by all objects.
public class Player {
String username; // Every player gets their own
static int globalPlayerCount = 0; // Shared across the entire app!
public Player() {
globalPlayerCount++; // Every time a new player is born, increment the global tracker!
}
}
[!WARNING] Do not overuse
static. It is effectively a Global Variable mechanism, which breaks the isolation principles of OOP. If multiple threads try to modify a static variable simultaneously, your application will experience catastrophic race conditions.