static 修饰符

package com.xuexi;
//static 修饰符,用来修饰类方法和类变量
//静态变量:static 关键字用来声明独立于对象的静态变量,无论一个类实例化多少对象,它的静态变量只有一份拷贝。 静态变量也被称为类变量。局部变量不能被声明为 static 变量。
//静态方法:static 关键字用来声明独立于对象的静态方法。静态方法不能使用类的非静态变量。静态方法从参数列表得到数据,然后计算这些数据。
public class Test1 {
private static int numInstances = 0;
protected static int getCount(){
return numInstances;
}
private static void addInstance(){
numInstances++;
}
Test1() {
Test1.addInstance();
}

public static void main(String[] args) {
System.out.println("Starting with "+Test1.getCount()+" instances");
for(int i = 0; i<500;++i){
new Test1();
}
System.out.println("Created "+Test1.getCount()+" instances");
}
}
原文地址:https://www.cnblogs.com/husband/p/14254523.html