Java Variable Scope Analogy: A Passenger on an Airplane
This analogy was developed in response to a student's question about when to use
this.variable and when to use
variable within a class's constructor:
Java “looks” for variables in a similar way to how you look for a magazine when you're on an airplane. First, you look in the seat pocket because that's closest to you, then in your carry on under the seat, then the carry on in the overhead compartment.
Java does something similar: it looks for the variable (magazine) closest to it.
So, first Java looks within the method/constructor to see if there is a variable named magazine in “here”, i.e., in the parameters that were passed in or in local variables. If the variable has not been defined, then it looks at the instance variables for the variable named “magazine”.
However, if the magazine you want is not the “SkyMall” magazine in the seat pocket but actually the magazine in your carry on, then you can specify that magazine directly by saying
this.magazine. (Think of
this.magazine as your object's magazine whereas the SkyMall magazine is the one that was passed in as a parameter.)
If you want the magazine that is in the overhead compartment (your parent class's variable), then you can call it