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 trialMartynas Kairys
4,959 Pointswhat is the difference between variable and member variable?
I understand there are several types of variables in Java. Can anyone explain what are the differences?
1 Answer
Craig Dennis
Treehouse TeacherA member variable is just part of the class. It is just like the other variables we have been creating, but it belongs to the instance of that class.
That make sense?
amathiaitishar
13,229 Pointsamathiaitishar
13,229 PointsSimple! A local variable is the variable you declare in a function. A member variable is the variable you declare in a class definiton. Hmm... Still confused?
When we define a class, we can give that class member variables. These variables are members of that class. Take, for example, the following class declaration.
The class VanillaGodzilla has two member variables, a & b. When we define an object instance of VanillaGodzilla it will still have two member variables, a & b. We can reference these members using the '.' dot character.
// Create an instance of VanillaGodzilla
VanillaGodzilla obj = new VanillaGodzilla();
// Assign new values to a & b
These variables belong to VanillaGodzilla, and are known as member variables. On the other hand, if we declare variables inside of a function, we call these local variables. These variables are local to a particular function, and not publicly accessible.
For example, in the following function, we have no way of accessing the obj variable outside of the main (String[]) function.
I have struggled quite a lot before I had it crystal clear and hopefully this helps. Best,