3.8 Scope and Access

0 阅读1分钟

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 block in which they are declared. (!!!) (if, for, {})
  • A method parameter is a local variable and 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 variables inside a method (header of body), and can only used inside the method.
    • Example:
      image.png
  • Local variables can also be declared inside a block of code(header or body), and can only be used inside the code block.
    • Example:
      image.png
      • 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.
  • Since constructors and methods are blocks of code, parameters to constructors or methods are also considered local variables.
  • public or private can not be used with local variables.
  • public or private is normally used 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 variable instead of the instance variable within the body of the constructor or method. image.png

3. Exercises