Unit 3 Cycle 1 Day 7: Static vs Instance
Share
Static vs Instance
Section 3.7 — Static Variables
Key Concept
Static variables belong to the class, not to any individual object. All instances share the same static variable, so changing it through one object affects all objects. A common use is counting the number of instances created: a static variable increments in the constructor. In contrast, instance variables are unique to each object. The AP exam tests whether you understand that ClassName.staticVar and obj.staticVar access the same variable, while obj1.instanceVar and obj2.instanceVar are independent.
Consider the following class.
What is printed after executing: Ticket t1 = new Ticket(); Ticket t2 = new Ticket(); Ticket t3 = new Ticket(); System.out.println(t1.getId() + " " + t3.getId());
Answer: (A) 1 3
Static nextId is shared across all objects. t1: id=1, nextId becomes 2. t2: id=2, nextId becomes 3. t3: id=3, nextId becomes 4. t1.getId()=1, t3.getId()=3.
Why Not the Others?
(B) Each Ticket gets a unique id because nextId increments after each construction.
(C) t1 was created first and got id=1, not 3.
(D) nextId starts at 1, not 0.
Common Mistake
Static variables are shared by ALL instances of a class. When one object modifies a static variable, the change is visible to all other objects. Each instance has its own copy of instance variables.
AP Exam Tip
Static = belongs to the class (shared). Instance = belongs to each object (unique). A static counter in a constructor assigns unique IDs.