无论一个类实例化多少对象,它的静态变量只有一份拷贝

static 修饰符

  • 静态变量:

    static 关键字用来声明独立于对象的静态变量,无论一个类实例化多少对象,它的静态变量只有一份拷贝。 静态变量也被称为类变量。局部变量不能被声明为 static 变量。

  • 静态方法:

    static 关键字用来声明独立于对象的静态方法。静态方法不能使用类的非静态变量。静态方法从参数列表得到数据,然后计算这些数据。

对类变量和方法的访问可以直接使用 classname.variablename 和 classname.methodname 的方式访问。

 两段代码很好地解释了静态变量只有一份拷贝:

static修饰:

package hello;

public class Static {
	private static int count=0;
	//private int count=0;
	
	public static int getCount() {
		return count;
		
	}
	
	private static void add(){
		count++;
	}
	
	
	Static() {
		// TODO Auto-generated constructor stub
		add();  
	}
	
//	Static(String s){
//		
//	}
	public static void main(String[] args) {
		Static static1 =new Static();
		System.out.println("start:"+static1.getCount());
		for(int i=0;i<10;i++){
			static1=new Static();
		}
		System.out.println("end:"+static1.getCount());
	}
}




 result:

 没有static修饰:

package hello;

public class noStatic {
	private  int count=0;
	//private int count=0;
	
	public  int getCount() {
		return count;
		
	}
	
	private  void add(){
		count++;
	}
	
	
	noStatic() {
		// TODO Auto-generated constructor stub
		add();  
	}
	
//	Static(String s){
//		
//	}
	public static void main(String[] args) {
		noStatic static1 =new noStatic();
		System.out.println("start:"+static1.getCount());
		for(int i=0;i<10;i++){
			static1=new noStatic();
		}
		System.out.println("end:"+static1.getCount());
	}
}




result:

 

猜你喜欢

转载自blog.csdn.net/haohao0626/article/details/84402197