Variables y Métodos de Clase
Introducido| English | Significado |
|---|---|
| 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; }
}
Un contador estático compartido
count es un valor compartido, propiedad de la clase.
Una variable estática (de clase) es...
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
estático significa una copia compartida propiedad de la clase.
Si el constructor hace count++ y count comienza en 0, ¿cuál es count después de crear 3 objetos?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
Cada construcción incrementa el contador compartido → 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.
Dentro de la clase Student mostrada, un método estático puede usar return score; sin especificar ningún objeto Student.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Falso: score es un campo de instancia y este método estático no tiene un receptor implícito. Con un parámetro s de tipo Student no nulo, return s.score; es válido dentro de Student.
Dentro de Student, ¿qué método estático puede leer la puntuación de un parámetro s no nulo?
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
La referencia explícita s identifica el objeto; Student misma puede acceder a su campo privado score.
Trace class and object calls
- After
Student a = new Student(50);andStudent 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.
Un método de instancia como getScore() se llama sobre...
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Los miembros de instancia actúan sobre un objeto específico.
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.
¿Cuál llamada muestra mejor que getCount() es un método estático de Student?
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Student.getCount() nombra claramente la clase. Java también permite student.getCount() para un método estático, pero esa ortografía oscurece su significado a nivel de clase.
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.
Se han construido dos estudiantes, por lo tanto count es 2. Luego se ejecuta Student alias = a; y alias.setScore(90);. ¿Qué devuelve Student.getCount()?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
Ni asignar una referencia ni cambiar una puntuación ejecutan el constructor. El valor de count permanece en 2.
Este contador de constructores disminuye automáticamente cuando se pierde una referencia a un estudiante.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Solo el código que cambia count lo modifica. Este ejemplo cuenta las construcciones y no proporciona ninguna disminución.