java 奇怪问题
public class B
{
public static int variable=A.flag;
};
public class A
{
public static int flag=22;
public A()
{
flag++;
System.out.println( " in Constructor method variable= "+Integer.toString(B.variable));//B.variable=10;
flag=40;
System.out.println( " in Constructor method variable= "+Integer.toString(B.variable));//B.variable=10;
}
public static void changeValue()
{
flag=30;
System.out.println( " in changeValue method variable= "+Integer.toString(B.variable));
}
public static void main(String[] args)
{
A a = new A();
System.out.println( " in static method variable= "+Integer.toString(B.variable));
A.flag=20;
System.out.println( "in static method variable= "+Integer.toString(B.variable));
A.changeValue();
A b = new A();
}
};
输入结果:
in Constructor method variable=23
in Constructor method variable=23
in static method variable=23
n static method variable=23
in changeValue method variable=23
in Constructor method variable=23
in Constructor method variable=23
请高手解释一下原因。thanks。分数不够,可以再给。
------解决方案--------------------staic的变量只会初始化一次,然后上面一直都是在改变flag的值,所以..................
------解决方案--------------------你这程序中
public static int variable=A.flag;
variable的赋值只在
flag++;
System.out.println( " in Constructor method variable= "+Integer.toString(B.variable));//B.variable=10;
只在此调用时初始化赋值了
而对于后面的对flag的改变,都没有影响到B.variable,因为static变量只初始化一次,后面就不再对其初始化,也就不再调用public static int variable=A.flag;
所以B.variable的值一直都是23
------解决方案--------------------学习,顺便给那么一点点分了
------解决方案--------------------应该是考察static变量是在什么时候初始化吧
当内存加载类B的时候,B.variable就是23了,而且就初始化一次,
所以始终就是23,
同意1,2楼
------解决方案--------------------就是static 的用法,在修饰变量时!
建议认真学习基础。