温馨提示×

java类变量怎么定义

小亿
81
2024-01-17 08:00:44
栏目: 编程语言

在Java中,类变量也被称为静态变量。可以通过在类的内部使用static关键字来定义类变量。类变量在整个类中都可见,可以被类的所有对象共享。

类变量的定义语法如下:

public class ClassName {
    static dataType variableName;
}

其中,dataType为数据类型,variableName为变量名。

例如,定义一个表示学生人数的类变量:

public class Student {
    static int studentCount;
}

在其他地方使用该类变量时,可以通过类名.变量名的方式访问,如:

Student.studentCount = 10;
System.out.println("学生人数:" + Student.studentCount);

输出结果为:学生人数:10

0