public class StaticTester {
public int x=1;
public static int y=1;
}
public class StaticTest {
public static void main(String[] args) { StaticTester.y+=1;
StaticTester t1=new StaticTester();
StaticTester t2=new StaticTester();
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 StaticTest {
public static void main(String[] args) { StaticTester.y+=1;
StaticTester t1=new StaticTester();
StaticTester t2=new StaticTester();
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
为什么?
也就是所有对y的操作都体现在每个对象上
:
1.非静态成员变量:以new的方式创建一个对像时,那么非静态成员变量为该对像的一个局布变量.此对像只可操作或改变他本身的成员变量的值;例:
StaticTester t1=new StaticTester();
StaticTester t2=new StaticTester();
t1.x = 10;
t2.x = 100;
System.out.println("t1.x:"+t1.x);
System.out.println("t2.x:"+t2.x);
out print :
t1.x:10
t1.x:100上例可以看出一个非静态成员变量.只能由对像本身来修改与删除
2.静态成员变:当一个对像定义了一个静态成员变量后.这个静态成员变量,将成为所以此对像实例的一个全局变量,有且只有一个这样的对像.(也就是初始化一次,无论创建多少个实例,它有且只有一个);
StaticTester t1=new StaticTester();
StaticTester t2=new StaticTester();
t1.y = 100;//给这个静态变量赋上100的值
t2.y +=10;//给这个静态变量加10
//t1 与 t2 都是StaticTester的实例,y又是StaticTester的一个静态成员变量,则有且只有一个这样的变量存在
//因此当StaticTester的任何实例去改变这个变量时,都是改变了同一变量.
//所以我们就说
System.out.println(t1.y == t2.y);//output true