先来看一段程序:
public class StaticTest02 {
public static void main(String args[]) {
Chinese c1 = new Chinese("1231456456456456","张三","中国");
System.out.println(c1.name);
System.out.println(c1.idCard);
System.out.println(c1.country);
Chinese c2 = new Chinese("7897897896748564","李四","中国");
System.out.println(c2.name);
System.out.println(c2.idCard);
System.out.println(c2.country);
}
}
class Chinese {
String idCard;
String name;
String country;
public Chinese() {
;
}
public Chinese(String s1, String s2, String s3) {
idCard = s1;
name = s2;
country = s3;
}
}
程序的结果没有任何的错误。我们再来看一下它的内存图:
可以看到,也没有任何的错误,接下来我们思考一个问题。
Chinese类型的对象无论有多少个,对象的属性country永远只有"中国"这个值,但在内存图中却出现了两块,这样不是浪费内存了吗。所以我们考虑到可以将属性country的值"中国"保存在一个固定的地方,我们需要时再调用。
接下来我们将变量country定义为static类型的,代码如下:
public class StaticTest02 {
public static void main(String args[]) {
Chinese c1 = new Chinese("1231456456456456","张三");
System.out.println(c1.name);
System.out.println(c1.idCard);
System.out.println(Chinese.country);/**通过类名.的方式访问*/
Chinese c2 = new Chinese("7897897896748564","李四");
System.out.println(c2.name);
System.out.println(c2.idCard);
System.out.println(Chinese.country);/**通过类名.的方式访问*/
}
}
class Chinese {
String idCard;
String name;
static String country = "中国";/**静态变量*/
public Chinese() {
;
}
public Chinese(String s1, String s2) {
idCard = s1;
name = s2;
}
}
static变量是在类加载当中创建的,所以存储在方法如区中,如下: