开发者

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; 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.

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.

A开发者_如何转开发bove code is slightly simplified for clarity.


Try qualifying mWorkout with this.

this.mWorkout = workoutFactory.createWorkout(); 

My assumption is that you have defined a local mWorkout that's shadowing your instance variable with the same name.


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. If you tried this.mWorkout = ... you might get a different result.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜