//private static int y=5; private static int x =getvalue(); // private static int y=5; public static int getvalue() { int y=5; return y; }
public static void main(String[] args) { System.out.println(x); } }
朋友,这个问题是这样的,x被申明为static型,这说明他将在该类第一次被调用时在该类的静态存储单元中被初始化,而且在整个程序执行过程中只有一份!那么当进入程序的时候在运行所有程序之前,程序一定会先初始化,这时成员变量被赋予“0”初值。int型的就被赋予0。然后在运行中程序发现内存中已经有了x静态变量,所以不会创建新的x。所以总是0,如果不将其定义为static,像下面这样,这个问题就解决了! private int x =getvalue(); private static int y=5; public static int getvalue(){return y;}
Y实际上为0.
当你拿到值之后Y才有了5.
所以你打印X就是0咯.
假设你把Y提到第一行写就会有5.
2.跳到getvalue:此时,y = 0;
3.x = y = 0;
4.y = 5;
5.打印。
2.跳到getvalue:此时,y = 0; //此时的,声明y的语句 private static int y=5;
//还没出来, getvalue()返回的y,从哪里冒出来的? 昏了
3.x = y = 0;
4.y = 5;
5.打印。
但建议还是手动为变量初始化。
public class C02 {
//private static int y=5;
private static int x =getvalue();
// private static int y=5;
public static int getvalue()
{
int y=5;
return y;
}
public static void main(String[] args)
{
System.out.println(x);
}
}
private static int y=5;
public static int getvalue(){return y;}
public static void main(String[] args)
{
C02 m=new C02();
System.out.println(m.x);
}
不好意思,刚才的回答还没有完整。
你也可以用下面的方法,让程序在执行过程中去修改x。而不应该向刚才那样希望在初始化的时候修改x
private static int x =getvalue();
private static int y=5;
public static int getvalue(){return y;}
public static void main(String[] args)
{
x=getvalue();
System.out.println(x);
}