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;
    }
}
Back to Blog

相关文章

阅读更多 »

Java 变量

什么是 Java 中的变量?变量是用于存储数据值的容器。Java 中变量的类型 本地变量 示例:java class Test { void dis...

接口 vs 抽象类

Interface 或 Abstract Class?它们非常相似,因此在何时使用每一种都会让人感到困惑。我将在这篇文章中回答这个问题。

第12天:理解 Java 构造函数

什么是 Constructor?Constructor 是 Java 中的特殊方法,在创建对象时会自动调用。- Constructor 的名称必须与类名相同……