Variáveis e Métodos de Classe
Introduzido| English | Significado |
|---|---|
| static variable/ˈstætɪk ˈveərɪəbl/ | Variável 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; }
}
Uma contagem estática compartilhada
count é um único valor compartilhado, pertencente à classe.
Uma variável estática (de classe) é...
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
static significa uma única cópia compartilhada pertencente à classe.
Se o construtor faz count++ e count começa em 0, qual é o valor de count após criar 3 objetos?
Dificuldade 2/5 · Moedas 140 + pequeno bônus na primeira conclusão hoje
Cada construção incrementa a contagem compartilhada → 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 da classe Student mostrada, um método estático pode usar return score; sem especificar nenhum objeto Student.
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
Falso: score é um campo de instância e este método estático não possui receptor implícito. Com um parêntese s não-nulo do tipo Student, return s.score; é válido dentro de Student.
Dentro de Student, qual método estático pode ler a pontuação de um parâmetro s não nulo?
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
A referência explícita s identifica o objeto; Student em si pode acessar seu campo score privado.
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.
Um método de instância como getScore() é chamado em...
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
Membros de instância atuam sobre um 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.
Qual chamada melhor demonstra que getCount() é um método estático de Student?
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
Student.getCount() nomeia claramente a classe. Java também permite student.getCount() para um método estático, mas essa grafia obscurece seu significado de nível de classe.
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.
Dois alunos foram construídos, então count é 2. Em seguida, Student alias = a; e alias.setScore(90); são executados. Qual é o valor de Student.getCount()?
Dificuldade 2/5 · Moedas 140 + pequeno bônus na primeira conclusão hoje
Nem atribuir uma referência nem alterar uma pontuação executa o construtor. A contagem permanece 2.
Este contador de construtores diminui automaticamente quando uma referência para um aluno é perdida.
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
Apenas código que altera count muda seu valor. Este exemplo conta construções e não fornece nenhum decremento.