Class Variables and Methods · Variables y Métodos de Clase
| English | Español |
|---|---|
| static variable/ˈstætɪk ˈveərɪəbl/ | variable estática |
| static method/ˈstætɪk ˈmeθəd/ | método estático |
Two objects, one construction count
- Ada and Bo have separate scores, but creating either student increases the same static variable 静态变量,
Student.count. After two constructions, the count is 2; changing Ada's score does not change Bo's score. - Compare what each value describes: a score describes one student, while this counter describes constructions of the class. A copied reference to Ada creates no new object and does not increment the counter.
Put each field at the right level
- An instance field has a separate storage location in each object. A static field has one storage location for this loaded class, even before any objects are constructed;
privatecontrols access, not the number of copies. - In this small single-threaded example, the constructor increases
countonce per construction. It counts objects constructed, not objects still alive: losing a reference does not automatically decrease it.
class Student {
private int score;
private static int count = 0;
public Student(int initialScore) {
score = initialScore;
count++;
}
public int getScore() { return score; }
public void setScore(int newScore) { score = newScore; }
public static int getCount() { return count; }
public static int readScore(Student s) { return s.score; }
}
One shared static count · Un contador estático compartido
count is one shared value, owned by the class.
A static (class) variable is...
static means one shared copy owned by the class.
If the constructor does count++ and count starts at 0, what is count after creating 3 objects?
Each construction increments the shared count → 3.
A static method has no receiver
- A static method 静态方法 has no implicit current object, so it cannot use
thisor an unqualified instance field such asscore.getCount()can readcountbecause that field belongs to the class. - Static does not forbid working with objects.
readScore(Student s)receives an explicit object reference and readss.score; it is insideStudent, where access to that private field is allowed. Heresmust be non-null.
return score; inside a static method is a compile-time error in this class. return s.score; inside the shown static method is valid: the reference identifies which student's score to read.
Inside the shown Student class, a static method may use return score; without specifying any Student object.
False: score is an instance field and this static method has no implicit receiver. With a non-null Student s parameter, return s.score; is valid inside Student.
Inside Student, which static method can read the score of a non-null parameter s?
The explicit reference s identifies the object; Student itself may access its private score field.
Trace class and object calls
- After
Student a = new Student(50);and · y Student b = new Student(75);,Student.getCount()is 2,a.getScore()is 50 andb.getScore()is 75.a.setScore(60)changes only Ada's score. Student.readScore(a)then returns 60 without constructing another student. The method is static, yet its explicit parameter identifies an existing object whose state it reads.
An instance method like getScore() is called on...
Instance members act on a specific object.
Separate legal syntax from clear style
- Prefer
Student.getCount()to show that the method belongs to the class. Java also permitsa.getCount()for this static method; that syntax does not make the count specific to Ada. a.getScore()is an instance call with Ada as its receiver.Student.getScore()is invalid here because the method needs an object and is not static; choose field and method kinds from their responsibilities.
Which call best shows that getCount() is a static method of Student?
Student.getCount() clearly names the class. Java also permits student.getCount() for a static method, but that spelling obscures its class-level meaning.
Predict a reference copy
- Starting with the two constructed students,
Student alias = a;leaves the construction count at 2.alias.setScore(90)changes Ada's existing object, soa.getScore()is 90 and Bo's score remains 75. - Count executions of
new Student(...), then trace each object's state separately. Neither an accessor call nor a reference assignment creates a student, and a static method may still read an explicitly supplied object.
Static fields store class state; instance fields store object state. Static methods have no this, but may use explicit object references. Prefer class-qualified static calls and distinguish construction counts from live-object counts.
Two students have been constructed, so count is 2. Then Student alias = a; and alias.setScore(90); run. What is Student.getCount()?
Neither assigning a reference nor changing a score executes the constructor. The count stays 2.
This constructor counter automatically decreases when a reference to a student is lost.
Only code that changes count changes it. This example counts constructions and supplies no decrement.