Java静态方法
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");
}
}输出结果
Started with 0 instances Created 500 instances
热门推荐
10 新年顾客简短祝福语大全
11 迎元旦平安祝福语简短
12 对公司年会祝福语简短
13 堂姐进新房祝福语简短
14 走正路的祝福语简短
15 爷爷庆生文案祝福语简短
16 牛年的吉祥祝福语简短
17 退休的祝福语简短精辟
18 剪纸送祝福语大全简短