Java 什么时候使用static

1 .先不使用static

public class StaticTest{
	public static void main(String[] args){
		Chinese c1 = new Chinese("11111111","zhang","中国");
		System.out.println(c1.idCard);
		System.out.println(c1.name);
		System.out.println(c1.country);
		Chinese c2 = new Chinese("22222222","li","中国");
		System.out.println(c2.idCard);
		System.out.println(c2.name);
		System.out.println(c2.country);
	}
}

class Chinese{
	String idCard;
	String name;
	String country;      //先声明为实例变量,实例变量使用new创建对象后,使用(对象.变量名)的方式访问
	public Chinese(){
		
	}
	public Chinese(String s1, String s2, String s3){
		idCard = s1;
		name = s2;
		country = s3;
	}
}

  内存图:

 2. 使用static修饰country

public class StaticTest01{
	public static void main(String[] args){
		System.out.println(Chinese.country);    //使用static修饰,静态变量可以直接使用(类名.变量名)的方式访问
		Chinese c1 = new Chinese("11111","zhang");
		System.out.println(c1.idCard);
		System.out.println(c1.name);
		Chinese c2 = new Chinese("222222","li");
		System.out.println(c2.idCard);
		System.out.println(c2.name);
	}
}

class Chinese{
	String idCard;
	String name;
	static String country = "中国";    //在这里使用静态变量,因为每一个Chinese的国籍都是中国
	public Chinese(){
		
	}
	
	public Chinese(String s1, String s2){
		idCard = s1;
		name = s2;
	}
}

  内存图:

 结论:

在Chinese这个例中,所有的Chinese都有不同的idCard和name,所以声明为实例变量,通过实例名访问;但是Country这个属性,每一个Chinese都是一样的,所以可以声明为static静态变量。

对象如果有共同的特征可以声明为静态变量,静态变量保存在方法区中可以节省内存空间,静态变量在类加载的时候初始化,不需要new对象,静态变量的空间就开辟出来了。

对象的特征都表现为不同的值则实例变量,实例变量在创建对象后保存在堆中。

原文地址:https://www.cnblogs.com/homle/p/14163238.html