Portée et Accès
Introduit| English | Sens |
|---|---|
| local variable/ˈləʊkl ˈveərɪəbl/ | variable locale |
| scope/skəʊp/ | portée |
| shadows/ˈʃædəʊz/ | masquage |
A local resets; a field remembers
- A method creates
int count = 0;, increments it and returns 1. Calling that method twice returns 1 both times because each invocation has a fresh local variable. - A method that increments an object's field instead returns 1 and then 2 for the same initially zero-valued object. Distinguish where a name is usable from how long the stored state is retained.

Scope concerns a name in source code
- The scope 作用域 of a declaration is the part of the program where its name can be used. A block local is in scope from its declaration through the remaining block; a for-loop variable is not available after that loop.
- Scope, access permission and lifetime answer different questions. A name may be out of scope even though an object it once referenced remains reachable through another reference; fields are not governed by the same declaration rule as block locals.
Initialize local variables before reading them
- A local variable 局部变量 is declared in a method or block. Java requires it to be definitely assigned before its value is read;
int x; return x;is a compile-time error, not an automatic return of zero. - Instance fields receive default values during construction before initializers and constructor code run. In the example, count starts at 0; that field belongs to each object and persists between its method calls.
public class ScopeCounter {
private int count;
public int localCount() {
int count = 0;
count++;
return count;
}
public int rememberedCount() {
count++;
return count;
}
public void setCount(int count) {
this.count = count;
}
public static int readCount(ScopeCounter other) {
return other.count;
}
}
La déclaration locale int x ; attribue automatiquement la valeur zéro à x, donc return x ; peut compiler.
Difficulté 1/5 · 100 pièces + un petit bonus lors de la première réussite aujourd'hui
Les variables locales doivent être définitivement assignées avant d'être lues ; les valeurs par défaut des champs ne s'appliquent pas aux variables locales.
A parameter can hide a field name
- The parameter
countinsetCount(int count)shadows 遮蔽 the field for unqualified uses of that name.count = count;would assign the parameter to itself;this.count = count;updates the receiver's field. - A local may shadow a field too, as localCount demonstrates. Do not infer that every duplicate local declaration is allowed: redeclaring an already in-scope local in a nested block of the same method is a compile-time error.
La portée d'une variable est...
Difficulté 1/5 · 100 pièces + un petit bonus lors de la première réussite aujourd'hui
La portée est là où le nom est valide.
Après la fin de l'appel d'une méthode ordinaire, l'appelant peut-il utiliser une variable locale déclarée uniquement à l'intérieur de cette méthode par son nom local ?
Difficulté 1/5 · 100 pièces + un petit bonus lors de la première réussite aujourd'hui
Le nom local n'est pas dans la portée de l'appelant. Un objet référencé par ce nom local peut néanmoins être retourné et rester accessible.
Quel type de variable devrait contenir l'état que l'objet doit retenir entre les appels de méthode ?
Difficulté 1/5 · 100 pièces + un petit bonus lors de la première réussite aujourd'hui
Les variables d'instance persistent pendant la durée de vie de l'objet.
Un paramètre portant le même nom qu'un attribut d'instance l'écrase (le cache) à l'intérieur de la méthode.
Difficulté 1/5 · 100 pièces + un petit bonus lors de la première réussite aujourd'hui
À l'intérieur de la méthode, le nom désigne le paramètre ; utilisez this pour accéder au champ.
Lorsqu'un paramètre cache un attribut d'instance du même nom, on dit qu'il ___ celui-ci (un seul mot).
Difficulté 1/5 · 100 pièces + un petit bonus lors de la première réussite aujourd'hui
L'écrasement cache le champ derrière le nom local.
Access depends on the declaring class
- Code inside ScopeCounter may read another ScopeCounter object's private count via an explicit reference. The shown static readCount method has no
this, butother.countis valid for a non-null parameter. - An unrelated external class cannot directly read that private field. Private access is not restricted to “only my own object”; an instance method has an implicit receiver, while a static method needs an explicit reference to access instance state.
Do not combine name scope, default initialization and private access into one rule. A local does not automatically start at zero, an instance field cannot be read unqualified from a static method, and a private field of another instance may be accessed inside its declaring class.
Portée, état du champ et permission d'accès
Distinguer les déclarations du contexte d'accès ; une autre instance n'est pas automatiquement inaccessible.
La méthode statique readCount affichée peut lire other.count lorsque other n'est pas null.
Difficulté 1/5 · 100 pièces + un petit bonus lors de la première réussite aujourd'hui
Il utilise une référence d'objet explicite et se trouve à l'intérieur de la classe qui déclare le champ privé ; aucun this implicite n'est nécessaire.
Predict a new receiver and a returned object
- After two rememberedCount calls on a, its field is 2; a newly constructed b still has count 0. Calling a.localCount() returns 1 without resetting a's field, because its local count shadows that field.
- A method can construct an object in a local variable and return its reference. The local name is then unavailable to the caller, but the returned object can remain reachable; the end of a name's scope does not destroy that object.
Scope tells where a name is usable; access modifiers control permission; object state can outlive a local reference. Initialize locals before reading them, use fields for per-object remembered state, and distinguish shadowing from access to another object's private field.
Pour un ScopeCounter a nouvellement construit, appelez a.rememberedCount() deux fois, puis a.localCount(). Que retourne a.localCount() ?
Difficulté 2/5 · 140 pièces + un petit bonus lors de la première réussite aujourd'hui
localCount possède un compteur local frais initialisé à zéro ; il incrémente et retourne 1 sans modifier le champ.