问题描述
- java这道题能帮我解答下么?最好能每行注释一下。麻烦各位大神
-
public class StaticTest {
static int x=1; int y;
StaticTest(){ y++; }public static void main(String args[ ]){
StaticTest st=new StaticTest();
System.out.println("x=" + x);
System.out.println("st.y=" + st.y);st=new StaticTest();
System.out.println("st.y=" + st.y);
}
static { x++;}
}
解决方案
public class StaticTest {
static int x=1;//静态变量,类加载时执行,只会执行一次
int y; //保存成员变量,没有赋值,默认为0
StaticTest(){ y++; }//构造方法
public static void main(String args[ ]){//main函数,程序执行入口
StaticTest st=new StaticTest();//这里实例化前执行加载,所以x=2.然后执行构造函数y=1
System.out.println("x=" + x);//x=2
System.out.println("st.y=" + st.y);//y=1
st=new StaticTest();//新的类,但是类加载只执行一次,所以x=2.同进,执行构造函数y=1
System.out.println("st.y=" + st.y);//y=1
}
static { x++;}//静态代码端,类加载时执行
}
解决方案二:
为什么没有初始化y的值?
解决方案三:
public class StaticTest {
static int x = 1; //定义静态整形变量x,并初始化赋值为1
int y;//定义变量y,默认值为0
/**
* 构造方法,给y赋值为1
*/
StaticTest() {
y++;
}
public static void main(String args[]) {
//构造StaticTest类的一个实例 st
StaticTest st = new StaticTest();
System.out.println("x=" + x);//输出x 值为
System.out.println("st.y=" + st.y);//输出y
st = new StaticTest();//这个就没有必要了~~
System.out.println("st.y=" + st.y);//输出y
}
//静态块,会在类初始话的的时候就加载,所以输出的x会是2
static {
x++;
}
}
时间: 2024-08-04 04:43:36