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);注释掉。
输出结果为:
绿色黄色
绿色红色
请问这是为什么呢?
{
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 = “绿色黄色红色”;
所以,接下来的输出都是“绿色黄色红色”;
而,非静态变量 是随对象而存在的;
而this.color+=color相当于字符串相加,字符串相加是接在原字符串后的
你实例化两次,分别为“黄色“,“红色”
所以最后结果连续输出了三次:绿色黄色红色相信现在你也知道去掉static之后结果变化的原因了。
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 = 绿色黄色红色
//因为你在创建实例的时候就已经把值赋值完毕 static 只会被加载一次
//所以你以下输出都是你所创建最后一个实例的值 也就是绿色黄色红色
System.out.println(sv1.color);
System.out.println(sv2.color);
System.out.println(color);
}
}大神们 如果小弟说错了 求狂批......求教育... 如果没错 也求大神在更进一步的指点....
我要是只打印
System.out.println(sv1.color);那他就不应该再输出“红色”了吧,可是结果还是输出“绿色黄色红色”,为什么呀,我没让他输出“红色”啊;这是为什呢
{
static String color = "绿色"; //当JVM加载的时候就会被第一个初始化
public staticvariable(String color)
{
this.color += color;
}
public static void main(String args[])
{
staticvariable sv1 = new staticvariable("黄色"); //1 . 此时创建了一个实例 此时 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追求内容 追加后的结果是 绿色黄色