Previously, I tried to write a single article that covered variable scope. The longer it got, the more I realized that was dumb. Covering everything a new programmer would need to know about variable scope is about like reading the "A" encyclopedia volume in one sitting. There's too much information for one go around.
When you're learning about computer science you always learn from someone who's been a computer scientist for a long time. After a couple years of programming concepts like variable scope become second nature. Can you imagine explaining to someone how to chew? It would be hard to remember that they need the explanation, let alone explain it to them well.
All that to say, let's break down variable scope and start by defining the concept.
A variable's "scope" is just a fancy way of saying "What parts of my program can this variable be accessed from?" If a variable is "in scope" for a certain line of code that means the code can access that variable. If a variable is "out of scope" that means the code cannot access it any longer.
At this point, it is good to note that Java has a concept usually called "visibility" that is controlled by access modifiers such as public, private, default, and package. These deal more with whether or not a variable can be seen outside of a java class, while scope deals more with where a variable can be seen inside of a class.
Let's look at a brief example:
In the above code snippet, we see the hello variable declared twice: Once inside the class, but outside of any methods (instance variable), and once inside of the main method (local variable).
Why should you care?
Instance variables and local variables are used in very different ways. Using them properly can make your code much more straightforward and also save you lots of time in the writing of it.
Click here for more on instance variables!
Click here for more on instance variables!
No comments:
Post a Comment