1

Java 变量作用域

 2 years ago
source link: https://painso.com/posts/tech/2020/java-variable-scope/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Aug 23, 2020

Java 变量作用域

Java 变量分为:

需要在变量前添加修饰符static,可以在方法中直接调用

public class Hello {
    static int number = 10; // 定义类变量
    public static void main(String[] args) {
        System.out.println(number);  // 直接调用
    }
}

定义格式为String <type> <name> = <value>;

实例变量从属于对象,使用时需要进行初始化

public class Hello {
    // 定义实例变量
    String name = "Benjamin";
    int age = 18;
    public static void main(String[] args) {
        Hello instance = new Hello() ; // new 一个当前的Hello对象
        System.out.printf("name: %s, age: %s\n",instance.name,instance.age);
        System.out.println("-------------------------------------------------");
        // 修改实例变量的值
        instance.name = "Bob";
        instance.age = 24;
        System.out.printf("name: %s, age: %s\n",instance.name,instance.age);

    }
}

定义在方法内部的变量,该方法体使用完后跟随销毁,无法被其他方法直接调用

public class Hello {

    public static void main(String[] args) {
        // 定义局部变量
        String name = "Benjamin";
        int age = 18;
        System.out.printf("name: %s, age: %s\n",name,age);
    }
}

javavariablescope

2020-08-23 08:50


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK