请大家看看这个关于static的代码
public class staticvariable
{
static String color = "绿色";
public staticvariable(String color)
{
this.color += color;
}
public static void main(String args[])
{
staticvariable sv1 = new staticvariable("黄色");
staticvariable sv2 = new staticvariable("红色");
System.out.println(sv1.color);
System.out.println(sv2.color);
System.out.println(color);
}
}
输出结果为:
绿色黄色红色
绿色黄色红色
绿色黄色红色
若把static String color = "绿色";改为 String color = "绿色";再把System.out.println(color);注释掉。
输出结果为:
绿色黄色
绿色红色
请问这是为什么呢?
[解决办法]
静态变量 是随类而存在的,而非对象;
执行staticvariable sv1 = new staticvariable("黄色");之后,this.color = “绿色黄色”;
执行staticvariable sv2 = new staticvariable("红色");之后,this.color = “绿色黄色红色”;
所以,接下来的输出都是“绿色黄色红色”;
而,非静态变量 是随对象而存在的;
[解决办法]
static 变量只实例化一次,所有对象共享一个Static String color
而this.color+=color相当于字符串相加,字符串相加是接在原字符串后的
你实例化两次,分别为“黄色“,“红色”
所以最后结果连续输出了三次:绿色黄色红色
相信现在你也知道去掉static之后结果变化的原因了。
[解决办法]
我的理解 不知道理解的对不
- Java code
public class staticvariable {static String color = "绿色"; //当JVM加载的时候就会被第一个初始化 public staticvariable(String color){this.color += color;}public static void main(String args[]){staticvariable sv1 = new staticvariable("黄色"); //1 . 此时创建了一个实例 此时 color = 绿色黄色staticvariable sv2 = new staticvariable("红色"); // 2. 此时有创建了一个实例 此时 color = 绿色黄色红色//因为你在创建实例的时候就已经把值赋值完毕 [color=#FF0000] static 只会被加载一次 [/color] //所以你以下输出都是你所创建最后一个实例的值 也就是绿色黄色红色System.out.println(sv1.color); System.out.println(sv2.color);System.out.println(color);}}
[解决办法]
你应该搞清楚代码的执行顺序
当编译的时候首先static会被放到静态域中
static String color = "绿色";
当你去创建这个类的实例时候staticvariable sv1 = new staticvariable("黄色");
你会调用他的构造方法
public staticvariable(String color)
{
this.color += color;
}
最后你输出的时候结果肯定会变的
整理下大概过程是
//加载静态属性
1. static String color = "绿色";
//创建实例
2. staticvariable sv1 = new staticvariable("黄色");
//调用有参构造方法
3. public staticvariable(String color)
//给color 追求内容
4.this.color += color;
//color此时等于绿色黄色
5.JVM给color追求内容 追加后的结果是 绿色黄色