These notes recap Topic 3.7. Full explanations and worked examples are in the study guide.
Recap
- Class variables belong to the class. All objects share a single copy. They are declared with
staticbefore the type. - A
publicclass variable is accessed outside the class with the class name and dot operator, for exampleMember.MAX_BORROW. - Class methods (
static) can access and change class variables and call other class methods. - Class methods cannot access or change instance variables or call instance methods unless they are passed an instance as a parameter.
- A
finalvariable cannot be modified. Constants are usuallypublic static final. - Typical uses: counting objects created, and giving each object a unique identifier.
Key relationships
| Feature | Declared | Copies | Accessed with |
|---|---|---|---|
| Instance variable | private int id; |
One per object | An object (inside its methods) |
| Class variable | private static int nextId; |
One for the class | Class methods, instance methods, constructors |
| Constant | public static final int MAX = 4; |
One, unchangeable | ClassName.MAX |
| Instance method | public int getId() |
Operates on one object | An object: a.getId() |
| Class method | public static int getCount() |
Belongs to the class | ClassName.getCount() |
Worked reminder
Member gives each new object id = nextId then increments nextId. After three constructions the ids are 1, 2 and 3, and Member.getCount() is 3. In Tally, hit() increases both the per-object mine and the shared all. After p.hit() twice, q.hit(), Tally.reset() and q.hit() the values are p.mine 2, q.mine 2 and all 1, so the output is 2 2 1. Shop.withTax(80.0) is 100.0 when TAX_RATE is 0.25.
Compile errors to recognise
| Message | Cause |
|---|---|
non-static variable id cannot be referenced from a static context |
Class method uses an instance variable with no instance |
non-static method getId() cannot be referenced from a static context |
Class method calls an instance method with no instance |
cannot assign a value to static final variable LIMIT |
Assigning to a constant |
Mistakes to avoid
- Declaring a counter as an instance variable when it needs to be shared.
- Resetting a shared counter inside the constructor.
- Using
thisor an instance variable in a class method (Topic 3.9 coversthis). - Calling a class method through an object instead of the class name (it works, but is poor style).
- Confusing
staticwithfinal.
Quick self-check
- Three
Orderobjects are created. How many copies of astatic int ordersPlacedexist? Answer: one. - Can
public static int total() { return count; }compile ifcountis an instance variable? Answer: No. - How do you read
public static final int LIMITfrom another class? Answer:ClassName.LIMIT. - Which is the right place to increment a shared counter of objects created? Answer: in the constructor.