1. Exam Points
- Distinguish
instance variables and local variables(which is used).Local variables declared in a method can only be accessed in the method.Local variables declared in a code block can only be accessed in the blockin which they are declared. (!!!) (if, for, {})A method parameter is a local variableand can only be used in the declaring method.The name refers to the local variable if a local variable has the same name as an instance variable.Local variables can not be declared as public or private.
2. Knowledge Points
(1) Scope and Access
Local variables(局部变量)are variablesinside a method(header of body),and can only used inside the method.- Example:
- Example:
Local variables can also be declared inside a block of code(header or body), andcan only be used inside the code block.- Example:
- In this example, i is declared in the header of a for loop, and can only be used inside the loop; y is declared in the body of an if block, and can only be used inside the if block.
- Example:
- Since constructors and methods are blocks of code,
parametersto constructors or methods are also consideredlocal variables. public or private can not be used with local variables.public or privateis normallyused for instance variables and class variables, these two are global variables(全局变量).- When there is a
local variable or parameter with the same name as an instance variable,the variable name will refer to the local variableinstead of the instance variable within the body of the constructor or method.