Max Koretskyi
Max Koretskyi

Reputation: 105497

final variable might not have initialized

I have code like this within a method:

final TouchableSpan touchableSpan = new TouchableSpan() {

    @Override
    public void onClick(View widget) {
        this.setPressed(true);

        String extravar = touchableSpan.getMyVar();
    }

On this line String extravar = touchableSpan.getMyVar(); I get a warning that variable touchableSpan might have not been initialized. Why is there?

This warning appeared when I added final modifier. Before I had variable is access from inner class, needs to be declared final.

Upvotes: 6

Views: 805

Answers (1)

Tagir Valeev
Tagir Valeev

Reputation: 100219

You first create an anonymous class and then assign it to the final variable. Thus your onClick method theoretically might be called before final variable initialization. Why not just using this.getMyVar()?

Upvotes: 9

Related Questions