集册 Java实例教程 范围类演示了字段和局部变量的范围。

范围类演示了字段和局部变量的范围。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

631
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
范围类演示了字段和局部变量的范围。

public class Main {

  // field that is accessible to all methods of this class

  static int x = 1;// from NowJava.com


  public static void main(String[] args) {

    int x = 5; // method's local variable x shadows field x


    System.out.printf("local x in main is %d%n", x);


    useLocalVariable(); // useLocalVariable has local x

    useField(); // useField uses class Scope's field x


    System.out.printf("%nlocal x in main is %d%n", x);

  }


  // create and initialize local variable x during each call

  public static void useLocalVariable() {

    int x = 25; // initialized each time useLocalVariable is called
//n o w j a v a . c o m - 时代Java

    System.out.printf("%nlocal x on entering method useLocalVariable is %d%n",

        x);

    ++x; // modifies this method's local variable x

    System.out.printf("local x before exiting method useLocalVariable is %d%n",

        x);

  }


  // modify class Scope's field x during each call

  public static void us
展开阅读全文