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 an Interactive Story App (Retired) Finishing the User Interface Loading Additional Pages

Ganta Hemanth
Ganta Hemanth
6,460 Points

scope of final variable in java

For a subclass to accsses a variable outside the subclass it should be final or a member variable. So why is the subclass able to access the final variable?? How does the final keyword work??

2 Answers

I agree with what Wesley Seago says but think his wording may be just as confusing. So my answer is just to clarify.

private String mNotFinal = "edit this text within this class or sub class";
private final String mFinal = "this text is set and cannot be changed";

// so...

mFinal = "I'm trying to change unchangeable text"; //  this line will NOT work

That is how the final keyword works for the most part.

Wesley Seago
Wesley Seago
10,424 Points

Using final guarantees the value won't be re-assigned. Lack of final when appropriate will usually cause a compile time error, rather than a runtime error.