Instance Variables and State

instance vars

Part of: Writing Classes

State Lives in Instance Variables The state of an object is everything it remembers about itself. In Java, that state is stored in instance variables (also called fields ). They are declared inside the class but outside any method , so every method of the object can use them. Because they live at the class level, instance variables exist for the entire lifetime of the object, unlike local variables which exist only while their method runs. Default Values If a constructor does not assign an instance variable, Java gives it a default value automatically: - numeric types (int, double) default to 0 / 0.0 - boolean defaults to false - object references (like String) default to null Local variables get no default, you must initialize them before use, or the compiler complains. Each Object Has Its Own State Because every object carries its own instance variables, changing one object never affects another: This independence is the whole point of objects: a and b model two separate counters. Naming and Scope Key distinctions to remember: - Instance variables describe object state and persist for the object's life. - Local variables and parameters exist only during a single method call. - In

Challenge: Score Keeper