Область видимости и доступность
Введено
7:25
Создание классов
Вот студент, хранящийся как три отдельных переменных: имя, курс и оценка. Это работает. Теперь добавьте тысячу студентов. Вам понадобятся три тысячи переменных…
Озвучивание на английском · переключаемые субтитры на английском и китайском языках
В этом уроке
| English | Значение |
|---|---|
| local variable/ˈləʊkl ˈveərɪəbl/ | Локальная переменная |
| scope/skəʊp/ | Область видимости |
| shadows/ˈʃædəʊz/ | Затенение |
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;
}
}
Локальное объявление int x; автоматически присваивает x значение нуля, поэтому return x; может скомпилироваться.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Локальные переменные должны быть определенно присвоены перед использованием; значения по умолчанию для полей к локальным переменным не применяются.
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.
Область видимости переменной — это...
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Область видимости — это место, где имя допустимо.
После завершения вызова обычного метода может ли вызывающий код использовать локальную переменную, объявленную только внутри этого метода, по ее локальному имени?
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Локальное имя не находится в области видимости вызывающего кода. Объект, на который указывает эта локальная переменная, тем не менее может быть возвращен и остаться доступным для использования.
Какой вид переменной должен хранить состояние, которое объект должен помнить между вызовами методов?
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Инстансные переменные сохраняются в течение жизни объекта.
Параметр с тем же именем, что и инстансная переменная, перекрывает (скрывает) эту инстансную переменную внутри метода.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Внутри метода имя означает параметр; используйте this для доступа к полю.
Когда параметр скрывает инстансную переменную того же имени, говорят, что он ___ ее (одно слово).
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Перекрывание скрывает поле за локальным именем.
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.
Область видимости, состояние поля и права доступа
Различайте объявления и контекст доступа; другой экземпляр не становится автоматически недоступным.
Показанный статический метод readCount может прочитать значение other.count, когда other не равен null.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Он использует явную ссылку на объект и находится внутри класса, объявляющего приватное поле; неявный this не требуется.
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.
Для только что созданного объекта ScopeCounter a вызовите a.rememberedCount() дважды, затем a.localCount(). Что вернет a.localCount()?
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
localCount имеет свежий локальный счетчик, инициализированный нулем; он увеличивает его и возвращает 1, не изменяя поле.
Что пошло не так? Это увидит только команда сайта.