[英]Java question about instance variables vs. local variables
Sorry if I'm missing something obvious here, but I'm confused about what's going on. 抱歉,如果我在这里遗漏了一些明显的东西,但是我对正在发生的事情感到困惑。 I declare
Workout mWorkout;
我宣布
Workout mWorkout;
as an instance variable at the top of my class. 作为我类顶部的实例变量。 Up until this point, it hasn't been initialized.
到现在为止,它尚未初始化。
This code works: createWorkout
returns a Workout object
, which is stored in the local variable test
, and then the instance variable mWorkout
is set from that. 这段代码有效:
createWorkout
返回一个Workout object
,该Workout object
存储在局部变量test
,然后从该mWorkout
中设置实例变量mWorkout
。
public void startWorkout() {
Workout test = workoutFactory.createWorkout();
mWorkout = test;
}
Whereas this code doesn't: 而此代码没有:
public void startWorkout() {
mWorkout = workoutFactory.createWorkout();
}
mWorkout
remains null
even though createWorkout
is still returning a Workout
object. 即使
createWorkout
仍返回Workout
对象, mWorkout
仍为null
。
Above code is slightly simplified for clarity. 为了清楚起见,上面的代码略有简化。
My bet is that somewhere in the non-working version of startWorkout
you have declared a method-scope instance of mWorkout
which is masking the instance field. 我敢打赌,在非工作版本某处
startWorkout
你声明的方法范围实例mWorkout
被掩盖实例字段。 If you tried this.mWorkout = ...
you might get a different result. 如果尝试了
this.mWorkout = ...
您可能会得到不同的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.