大多半天都有可能不明白,实践乃是检验真理的唯一标准,测试一下下面的代码,你就会明白了[size=30px]o(∩_∩)o[/size]public class Test { public static void main(String[] args) { Test1 t1a = new Test1(); Test1 t1b = new Test1();
Test2 t2a = new Test2(); Test2 t2b = new Test2(); } }public class Test1 { static { System.out.println("I am a static block."); } }public class Test2 { { System.out.println("I am not a static block."); } }
比如:初始化那些static 的变量,这些变量在那些static method里面需要使用!并且那些变量需要很多的步骤才能完成,一般采用如下方法比较好static {
initClass();
}
static void initClass(){
....
}
public static void main(String[] args) {
Test1 t1a = new Test1();
Test1 t1b = new Test1();
Test2 t2a = new Test2();
Test2 t2b = new Test2();
}
}public class Test1 {
static {
System.out.println("I am a static block.");
}
}public class Test2 {
{
System.out.println("I am not a static block.");
}
}
另外还有一个没有static的东西,叫初始化块,在构造之前调用class A{
A(){
System.out.println("构造A");
}
{
System.out.println("构造前调用")
}
}
class StaticTest {
public static int h = 100;
private int p;
static {
System.out.println("The static varaible is: " + h);
}
public static void incDisplay() {
System.out.println("Now, the static answer is: " + ++h);
}
public StaticTest() {
p = 10;
}
public void objectDisplay() {
System.out.println("The answer is: " + p);
}
}public class Test {
public static void main(String[] args) {
StaticTest.incDisplay();
StaticTest.incDisplay();
StaticTest test = new StaticTest();
test.objectDisplay();
}
}
2.不需要创建对象,就要访问某个方法而static就是这样一个关键字,声明了static后就表示上述两个目的