Scope
- Scope rules determine where in your code an identifier can be referenced.
- In Java, scope is determined by blocks of code (code within curly braces) and the class hierarchy of the current instance (more on hierarchies later, if time allows).
- When Java needs to resolve an issue of scope, it looks for an identifier's
definition in the following order (and stops looking when the identifier is
found):
- the current block
- surrounding blocks
- the class of the current instance (or current object)
- the superclasses of the current instance's class hierarchy
- This means that a local object with the same name as an instance
variable will be found and used, not the instance variable.
- It is a good idea to avoid using the names in a class or its superclass(es)
for local variables.
- If you do have local variables with the same identifier names and want to
access the instance variables, use this.
- An identifier can only be referenced within the same block in which it
has been declared, or if it has been declared in a surrounding block.
- Remember a block starts with an open curly brace and ends
with a close curly brace.
- Since the outer-most curly braces is the class, this is the last block searched.
- An object that is declared within a method's block of code surrounded by
curly braces is called a
local object.
- An object declared in a method's signature is called a local parameter.