public class Test { static {
Test t = null;
} public static void method() {
t = new Test();
}
}在这个例子中:t显示不能识别。。
怎么调用 静态块中的变量?
高手帮帮吗?
Test t = null;
} public static void method() {
t = new Test();
}
}在这个例子中:t显示不能识别。。
怎么调用 静态块中的变量?
高手帮帮吗?
要不这样
public class Test {
Test t;
static {
t = null;
}public static void method() {
t = new Test();
}
}
Test t;之前加static,还有静态块这样用没什么意义。。
首先,静态方法只能访问静态变量。
这句不是静态变量的定义方法,
定义静态方法应该是:static Test t = null;
这个明白。static 变量和静态块是一样的 用 javap 命令可查看。
我就是想在static块里声明一个变量 然后再static方法里调用试试
楼主没有弄明白域的概念,static块你可以把它当成一个方法你在一个方法里声明的局部变量在另一个方法里访问肯定是不行的这跟你是否static是没有关系的
我之前的理解是 static块里的内容和
static int a =10;
static{
int a =10;
}
是一样的。我觉得satic块不能把它当成方法。
有时间你用javap命令查看一下。上述几行代码的
编译效果
Test t = new Test();
method(t);
} public static void method(Test t){
t1 = t;
} public static void main(String[] args){
System.out.println(t1.i);
}
}
Test t = null;
}public static void method() {
t = new Test();
}
}
改成这样吧
public class Test{
} public class StaticTest{
private static test = null;
static{
test = new Test();
}
public static getInstance(){
return test;
} public static void main(string[] args){
Test test = StaticTest.getInstance();
...
}
}