Class Variables and Methods
| English | Chinese | Pinyin |
|---|---|---|
| static variable | 静态变量 | jìng tài biàn liàng |
| static method | 静态方法 | jìng tài fāng fǎ |
Shared by the whole class
- A static variable 静态变量 (class variable) is shared by every object of the class.
- Declare it with
static:private static int count; - There is one copy, owned by the class, not by any single object.
- Change it through one object and all objects see the new value.
A shared counter
- A classic use: count how many objects have been created.
- Increment the static
countin the constructor; it grows across all objects. - Each instance variable is per-object; the static variable is per-class.
- One shared value vs. many separate values — that's the core difference.
Static methods
- A static method 静态方法 does not act on an individual object's state.
- It belongs to the class and is called on the class name:
Math.sqrt(16). - It can't use instance variables or
this— there's no particular object. - Use static for general utilities (like
Math.max) that need no object.
static vs. instance members
- Static (class-level): one shared copy, called on the class name.
- Instance (object-level): one per object, called on an object.
Student.getCount()(static) vs.student.getScore()(instance).- Match the kind to the meaning: shared-across-all → static; per-object → instance.
A static member belongs to the CLASS — there's one shared copy, and a static method has no this. So a static method can't read an instance variable (whose object would it use?). Call static members through the class name (Student.getCount()), and instance members through an object (student.getScore()).
Counting Student objects:
private static int count = 0;- In the constructor:
count++;— shared across all Students. public static int getCount() { return count; }, called asStudent.getCount().
A static variable is shared by every object (one copy, owned by the class); a static method doesn't act on a single object's state and has no this. Call both through the class name. This contrasts with instance members — one per object, called on an object.
One shared static count
count is one shared value, owned by the class.
A static (class) variable is...
static means one shared copy owned by the class.
How do you call a static method getCount() of class Student?
Static members are called on the class name.
A static method can freely read the instance variables of a particular object.
A static method has no 'this' — no particular object to read from.
If the constructor does count++ and count starts at 0, what is count after creating 3 objects?
Each construction increments the shared count → 3.
An instance method like getScore() is called on...
Instance members act on a specific object.