Java 中的静态变量和非静态变量
发布: (2026年1月13日 GMT+8 23:45)
2 min read
原文: Dev.to
Source: Dev.to
非静态(实例)变量
在 Java 中,非静态变量声明在类内部但在任何方法之外,且不使用 static 关键字。每个类的对象都会拥有该变量的独立副本。
关键点
- 在创建对象时生成
- 每个对象拥有不同的值
- 存储在堆内存中
- 通过对象引用访问
示例
class Student {
int marks;
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();
s1.marks = 80;
s2.marks = 90;
System.out.println(s1.marks); // 80
System.out.println(s2.marks); // 90
}
}
这里,marks 是非静态变量,因此每个 Student 对象都有自己的值。
静态变量
静态变量属于类本身,而不是任何单独的对象。
关键点
- 类加载时创建一次
- 所有对象共享
- 存储在方法区
- 推荐使用类名访问
示例
public class Employee {
String name;
int salary;
static String company_name = "TCS";
public static void main(String[] args) {
Employee mukesh = new Employee();
mukesh.name = "Mukesh kumar";
mukesh.salary = 10000;
Employee hari = new Employee();
hari.name = "Hari krishnan";
hari.salary = 20000;
}
}