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

Java

Aren't Java class level variables supposed to be static?

One of the books I am reading on Java states that class level variables MUST be static, otherwise the program won't compile. I tried to compile a program in NetBeans with a non static class level variable and it failed to compile.

How did the sample program in the lesson compile and execute if the class level variable (mCharacterName) wasn't static?

1 Answer

Hi Adiv Abramson,

the variable mCharacterName is not a class variable but a member variable. Class variables are global that means that all objects access and alter the same variable. Very often class variables are used to count something, like the number of clients you have or how many cars have been produced etc. You could imagine it as only one and the same box where you put things of the same type in and out and you share this box with others.

Member variables are not shared like class variables. Every object/instance gets its own member variable like for example the name of a person object and thus will be different from the others. Imagine this as multiple boxes. Every box has its own owner. Maybe you have a box and put stuff in there, your friend has its own box and so on. This box is not shared and only for you.

If you put the keyword static before the declaration of a variable then you will create a class variable. Without this keyword the variable will be a member variable.

Could I clear things up a little? If you don't get it yet just write here again and I will try my best to explain it a little more in depth.