Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.