Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

final variable might not have initialized

Tags:

java

android

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.

like image 311
Max Koretskyi Avatar asked May 03 '15 07:05

Max Koretskyi


1 Answers

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()?

like image 79
Tagir Valeev Avatar answered Oct 07 '22 18:10

Tagir Valeev