Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Simple Android App (2014) Improving Our Code Simple Refactoring: Using a Class

What is the purpose of "final" on the TextView factLabel line? Why did we not have to do this for Button showFactButton?

I am not certain of the reason why final was used here.

1 Answer

Short answer: because factLabel is accessed in the OnClickListener and showFactButton isn't! If you assigned a value to showFactButton in the OnClick function you would have to make that variable final as well.

Longer answer: the OnClickListener is what is known as an inner class, and it behaves a bit differently than the code around it. Even though factLabel.setText("") looks like it is inside the OnCreate method, it it technically in a different class. Method variables (like our factLabel) only exist inside the method, so Java has to copy them over to the inner class so we can use them there. This introduces the possibility for a very subtle bug if we change the method variable after it's copied to the inner class. Instead Java forces us to declare the variable final, which means we can't change the value after we set it.

You can read more about this in this Stack Overflow question.