Java 编程中的 static 关键字
静态修饰符
静态变量
static 关键字用于创建将独立于为类创建的任何实例而存在的变量。无论类实例数多少,静态变量都只存在一个副本。
静态变量也称为类变量。局部变量不能声明为静态。
静态的方法
static 关键字用于创建将独立于为类创建的任何实例而存在的静态方法。
静态方法不使用其定义的类的任何对象实例变量。静态方法从参数获取所有数据,并通过这些参数计算某些内容,而无需引用变量。
可以使用类名称后跟点号和变量或方法名称来访问类变量和方法。
示例
静态修饰符用于创建类方法和变量,如下例所示 −
public class InstanceCounter {
private static int numInstances = 0;
protected static int getCount() {
return numInstances;
}
private static void addInstance() {
numInstances++;
}
InstanceCounter() {
InstanceCounter.addInstance();
}
public static void main(String[] arguments) {
System.out.println("Starting with " + InstanceCounter.getCount() + " instances");
for (int i = 0; i < 500; ++i) {
new InstanceCounter();
}
System.out.println("Created " + InstanceCounter.getCount() + " instances");
}
}输出
Starting with 0 instances Created 500 instances
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP