简体   繁体   English

关于实例变量与局部变量的Java问题

[英]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. 为了清楚起见,上面的代码略有简化。

Try qualifying mWorkout with this . 尝试与this mWorkout合格。

this.mWorkout = workoutFactory.createWorkout(); 

My assumption is that you have defined a local mWorkout that's shadowing your instance variable with the same name. 我的假设是,您定义了一个本地mWorkout ,该mWorkout用相同的名称遮盖了您的实例变量。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM