The example just shown goes against the notion of data encapsulation and good object-oriented programming techniques. However, you might need to work with variables whose values are shared across different method invocations. Even though it might not make sense to make
gGlobalVar an instance variable in the
Foo class, a better approach might be to “hide” it within the
Foo class by restricting its access to setter and getter methods defined for that class.
You now know that any variable defined outside a method is not only a global variable, but an external one as well. Many situations arise in which you want to define a variable to be global but not external. In other words, you want to define a global variable to be local to ...