Sunday, February 3, 2013

Variable Scope: Instance Variables


If you need an introduction and definition of variable scope, checkout my previous post.



Instance variables have "bigger scope" than local variables. Figuring out where they can be declared accessed from is easy: (Almost) Anywhere! (At least, almost anywhere inside of the class they're declared in.)

In the following example, we access the instance level variable in two different methods and use it for another instance level variable!



And this is completely legal, since instance variables can be accessed almost anywhere.

The almost part comes in the order that instance level variables are declared and used in. You can use an instance variable in a method before it is declared, but you cannot use an instance variable for another instance variable before it is declared.


In the above example, our wellHello string has a compiler error, while our references to hello in the main and printHello methods are fine. The compiler error states that you cannot use a variable before it is declared.

Why should you care?

Variable scope is a concept that can mostly be sorted out through trial and error. If you try to use a variable somewhere, and it's out of scope, the compiler will tell you. However, understanding variable scope can save you a lot of time when programming.

No comments:

Post a Comment