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

What is the purpose of member variables?

I'm working on the "Animating the Answer" in the beginning of the "build a simple android app" and Ben keeps re factoring variables as member variables. For instance, he refactored '''java private TextView mAnswerLabel '''

But what's the point of refactoring AnswerLabel is the name is going to be the same everywhere? Doesn't the computer see this as the same thing? (obviously not, which is why I'm asking for an explanation on the usage of member variables).

1 Answer

Ben Jakuben
STAFF
Ben Jakuben
Treehouse Teacher

This is an object-oriented programming concept that can be confusing at first.

The main idea is that all variables have a specific scope which depends on where a variable is defined (defined being where its data type and name are declared). So if a variable is defined in a method, like onCreate(), then it is only available inside that method. You can't reference it from anywhere else.

Class-level variables, or member variables, are defined at the class level, meaning they are available anywhere within that class. The reason we declare mAnswerLabel as a member variable is so that we can reference that same variable anywhere in the class, the MainActivity.java file. We need to use it in more than one method.

There are additional concerns about member variables that have to do with how they are available outside of the class, too. If you make them public, then any other class file can reference the values. If they are private, then they can only be referenced inside the class. This doesn't matter too much in the Crystal Ball project, but we'll work with this as we go through the projects. The main reason is to protect private data so that it isn't inadvertently accessed or changed in the wrong place.