At first glance, these seem equivalent. If one has the right visibility, one can access a global variable or a class variable from anywhere in the program; There is only one, shared copy of them. So why would a software engineer choose one over the other?

Considerations could assume a language like Python, with no private variables, or C++, with private variables.

New contributor
charmoniumQ is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • The term 'global variable' is pretty overloaded. In Python the term 'global' refers to module scope, for example. Java doesn't support a true 'global' nor does it refer to anything as such. We also use 'global' less formally to mean a variable in some scope that is accessed and/or modified from many places in an program. I think you might want to clarify a bit here what specifically you mean by 'global'.
    – JimmyJames
    Sep 21 at 19:26

1 Answer 1


Accessibility is not the only thing. There's also scope and context.

A class variable (or static member as they are called in many languages) is tied to a particular domain. It should make sense to make it a member of that class because it is meaningful in the context of that class.

Example: class Cat may have a static member count that keeps the number of Cat instances at any particular time. You could instead have a global variable catCount but that would be less OO. Obviously the number of Cat instances is closely related to the Cat class, hence it makes sense to make it a Cat class member. This also narrows the scope of the variable to the class members of Cat (you must type Cat. first for it to become available). Tight scope is always a good thing, a global variable catCount would be meaningless outside the scope of the Cat class and thus noisy.

  • I agree with much of this but OO purists don’t even recognize the need for classes, let alone hanging static members off of them. Try “less modern” or “less disciplined”. Sep 22 at 0:42

Your Answer

charmoniumQ is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.