class StaticTest{
public int x=1;
public static int y=1;
}
public class StaticTester { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
StaticTest.y+=1;
StaticTest t1=new StaticTest();
StaticTest t2=new StaticTest();
t1.x+=1;
t1.y+=1;
t2.x+=2;
t2.y+=2;
System.out.println("t1:x="+t1.x+",y="+t1.y);
System.out.println("t2:x="+t2.x+",y="+t2.y); }}
结果是t1:x=2,y=5
t2:x=3,y=5
想不通。求达人解答一下。
谢谢!
public int x=1;
public static int y=1;
}
public class StaticTester { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
StaticTest.y+=1;
StaticTest t1=new StaticTest();
StaticTest t2=new StaticTest();
t1.x+=1;
t1.y+=1;
t2.x+=2;
t2.y+=2;
System.out.println("t1:x="+t1.x+",y="+t1.y);
System.out.println("t2:x="+t2.x+",y="+t2.y); }}
结果是t1:x=2,y=5
t2:x=3,y=5
想不通。求达人解答一下。
谢谢!
StaticTest t1=new StaticTest(); //这里后。y的值存在内存中,不变(因为没作任何操作)t1.x=1
StaticTest t2=new StaticTest(); //这里后。y的值存在内存中,仍不变(因为没作任何操作)t2.x=1t1.x+=1; //t1.x=2
t1.y+=1; //直接使用内存中存在的y。这里结果为3
t2.x+=2; //t2.x=3;
t2.y+=2; //直接使用内存中存在的y。结果为5
x = 3, y = 5;为什么不是这样的呢 是因为这个static 用这个static所修饰的变量 意味着他不会和包含他的那个类的任何对象关联在一起你也可以这样认为 就是所有的StaticTest对象都共享同一个y 共用同一个y
StaticTest.y+=1;//y=2
StaticTest t1=new StaticTest();//x=1,y=2
StaticTest t2=new StaticTest(); //x=1,y=2
t1.x+=1; //x=2
t1.y+=1; //y=3
t2.x+=2; //x=3
t2.y+=2; //y=5System.out.println("t1:x="+t1.x+",y="+t1.y);//取 指向y的值,所以是最后一次y改变的值
System.out.println("t2:x="+t2.x+",y="+t2.y); //取 指向y的值,所以是最后一次y改变的值
当修饰属性时,类中的所有方法共享该变量。
当修饰方法时,该方法为静态方法,可以使用static修饰的属性/方法或变量,其他则不可以,不能使用this/super。
t1:x = 2, y = 3;
t2:x = 3, y = 5;
y是类变量
x是实例变量StaticTest.y+=1; //y是static变量(类变量),常驻内存。类加载时就创建了,当加载第二次时,内存中还存在,直接使用。这里值从1变成了2
StaticTest t1=new StaticTest(); //这里后。y的值存在内存中,不变(因为没作任何操作)t1.x=1;t1.y=2
StaticTest t2=new StaticTest(); //这里后。y的值存在内存中,仍不变(因为没作任何操作)t2.x=1 ;t2.y=2t1.x+=1; //t1.x=1+1=2
t1.y+=1; //直接使用内存中存在的y。这里结果为2+1=3
t2.x+=2; //t2.x=1+2=3;
t2.y+=2; //直接使用内存中存在的y。结果为3+2=5
其他类会公用这个static变量。
其实t1.y,t2.y,StaticTest.y三个是同一个变量,对谁操作都一样的