Java 变量类型
局部变量、成员变量(实例变量)与类变量(静态变量)的区别。
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.
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();
}
}age = 7variable 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.
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);
}
}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.
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);
}
}3
4
4Java 局部变量
局部变量声明在方法、构造方法或代码块内,只在所在块内有效。它没有默认值,使用前必须显式赋值,否则编译不通过。
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();
}
}age = 7variable age might not have been initialized —— 这是编译错误,不是运行时异常。成员变量(实例变量)
实例变量声明在类里、方法外,不加 static。每个对象各有一份,创建对象时分配,有默认值(数字 0、布尔 false、引用 null)。
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);
}
}null
0
0.0
false
Tom 28类变量(静态变量)
加 static 的字段是类变量,整个类只有一份,所有对象共享,用 类名.变量 访问最清晰。适合计数、全局配置这类「属于类而不属于对象」的数据。
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);
}
}3
4
4