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 trialRoy Korenblit
1,209 PointsShouldn't the answer variable be final?
We are only initializing it once, and i don't think we really want it to change afterwards. Just confused and wanted to be sure about this. Thanks for any help!
1 Answer
Lukas Dahlberg
53,736 PointsI think this is a pretty good question to think about, but I would say, for the purposes of the video that using the final keyword might end up leading into territory that an introduction to Java Objects doesn't need to cover. The reason for this is that the final keyword has different meanings depending on where it's used (for instance, a final class cannot be extended) which could lead to a high level of confusion to a total beginner in OOP.
However, if you were coding this in real life, you would want to use the final keyword so that the answer cannot be overridden in any fashion (and, extending this, you could employ what's called the Immutability Pattern to guarantee that the answer's state will always be the same; forcing the user to create a new instance, in a new game, if they want a new answer).
Also, the Java compiler contains the concept of 'effectively final'. So it'll optimize the code for you, under the covers, by treating the variable as final for you when it is set once and never modified. (An especially important feature when it comes to the advanced functional programming features of Java, specifically lambdas.)
If you are finding yourself questioning when and where to use keywords and how they work, I would highly suggest reading an Oracle Certification guide such as Mala Gupta's book ( https://www.amazon.com/OCA-Java-Programmer-Certification-Guide/dp/1617293253). Even if you don't want to get the certification (or certifications, as there's an Associate and Professional levels), they will give you a lot of insight into how Java is designed as a language - leading to your becoming a better Java programmer.
Roy Korenblit
1,209 PointsRoy Korenblit
1,209 PointsGreat answer. Thanks! you really cleared it up for me.