Java 变量类型

局部变量、成员变量(实例变量)与类变量(静态变量)的区别。

Beginner
Key Points局部变量在方法内、必须显式初始化;实例变量每个对象一份、有默认值;类变量加 static、全类共享一份。

Java 局部变量

A local variable lives inside a method, constructor or block and is visible only there. It has no default value and must be assigned before use, or the code will not compile.

Java
public class LocalVar {
    public void show() {
        int age = 0;
        age = age + 7;
        System.out.println("age = " + age);
    }

    public static void main(String[] args) {
        new LocalVar().show();
    }
}
Output
age = 7
Using an uninitialised local variable fails at compile time with variable age might not have been initialized — a compile error, not a runtime one.

成员变量(实例变量)

Instance variables are declared in the class body outside methods without static. Each object gets its own copy, allocated on creation with defaults: 0 for numbers, false for boolean, null for references.

Java
public class Employee {
    String name;
    int age;
    double salary;
    boolean active;

    public static void main(String[] args) {
        Employee e = new Employee();

        System.out.println(e.name);
        System.out.println(e.age);
        System.out.println(e.salary);
        System.out.println(e.active);

        e.name = "Tom";
        e.age = 28;
        System.out.println(e.name + " " + e.age);
    }
}
Output
null
0
0.0
false
Tom 28

类变量(静态变量)

A static field is a class variable: one copy for the whole class, shared by all objects, best accessed as ClassName.field. Use it for counters and global configuration — data that belongs to the class, not an object.

Java
public class Counter {
    static int total = 0;
    int id;

    Counter() {
        total++;
        id = total;
    }

    public static void main(String[] args) {
        new Counter();
        new Counter();
        new Counter();

        System.out.println(Counter.total);

        Counter c = new Counter();
        System.out.println(c.total);
        System.out.println(c.id);
    }
}
Output
3
4
4

Friends & Partners