public class Test {
static int a=1;
static {
new InnerStaticClass();
}
static int b=2;
static {
System.out.println("b="+b);
}
static class InnerStaticClass{
InnerStaticClass(){
System.out.println("a="+a);
System.out.println("b="+b);
}
}
public static void main(String[] args) {
new Test();
}
}
先执行静态变量,再执行静态代码块
所以答案是
a=1
b=2
b=2结果不对,求解,谢谢
static int a=1;
static {
new InnerStaticClass();
}
static int b=2;
static {
System.out.println("b="+b);
}
static class InnerStaticClass{
InnerStaticClass(){
System.out.println("a="+a);
System.out.println("b="+b);
}
}
public static void main(String[] args) {
new Test();
}
}
先执行静态变量,再执行静态代码块
所以答案是
a=1
b=2
b=2结果不对,求解,谢谢
b=0
b=2
应该是这一个结果 应该是先执行静态代码块 在初始化静态变量
static int a = 1;
static int b = 2;
static {
new InnerStaticClass();
}
static {
System.out.println("b=" + b);
} static class InnerStaticClass {
InnerStaticClass() {
System.out.println("a=" + a);
System.out.println("b=" + b);
}
} public static void main(String[] args) {
new Test();
}
}
这样的结果就是 1,2,2 了 静态变量和静态块谁在前面先执行谁
即
static int xxx = yyy;相当于 static int xxx;//声明指令 和 xxx = yyy; //赋值指令
声明指令是为变量分配内存空间,赋值指令是把值保存到变量内存空间,声明指令在编译期间相对内存空间就已经被固定好,方法栈被创建时,就自动把变量和该内存空间联系起来。static int a=1;
static {
new InnerStaticClass();
}
static int b=2;
static {
System.out.println("b="+b);
}
static class InnerStaticClass{
InnerStaticClass(){
System.out.println("a="+a);
System.out.println("b="+b);
}
}
相当于
static int a; //自动初始化为0
static int b; //自动初始化为0
static {a=1;}
static {
new InnerStaticClass();
}
static {b=2;}
static {
System.out.println("b="+b);
}
static class InnerStaticClass{
InnerStaticClass(){
System.out.println("a="+a);
System.out.println("b="+b);
}
}
所以一上来,就先为a和b分配内存空间,并初始化为0
然后执行执行 a=1,然后调用 new InnerStaticClass(); 然后执行 b=2; 然后执行System.out.println("b="+b);
这样,LZ就应该知道是什么结果了吧。
b=0
b=2
因为是static所有就按照顺序执行啊
static class InnerStaticClass {
InnerStaticClass() {
System.out.println("a=" + a);
System.out.println("b=" + b);//这个b没有被定义呀
}
}