多说无益,直接看代码。
public classMyTest {public static voidmain(String[] args)
{
Test t1= newTest();
System.out.println("------------");
Test t2= new Test(11);
System.out.println("------------");
}
}classTest
{private static int b =initializeB();private static int a =initializeA();private int c =initializeC();private static intinitializeA()
{
System.out.println("Initialize a in private static method");return 1;
}private static intinitializeB()
{
System.out.println("Initialize b in private static method");return 1;
}protected final intinitializeC()
{
System.out.println("Initialize c in private method for each object");return 1;
}static //Only called once at class load time
{
System.out.println("C# Static Constructor Equivalent\n====Static Initialization is done====");
}//Called every time before the constructor//This is shared among all the constructors.
{
System.out.println("Non-static shared block");
}publicTest()
{
System.out.println("In the constructor without parameter");
}public Test(intuseless)
{
System.out.println("In the constructor with only 1 parameter");
}
}
Console:
Initialize b in private static method
Initialize a in private static method
C# Static Constructor Equivalent
====Static Initialization is done====
Initialize c in private method for each object
Non-static shared block
In the constructor without parameter
------------
Initialize c in private method for each object
Non-static shared block
In the constructor with only 1 parameter
------------
Double Brace Initialization:
See: http://www.c2.com/cgi/wiki?DoubleBraceInitialization
The first brace creates a new AnonymousInnerClass, the second declares an instance initializer block that is run when the anonymous inner class is instantiated. This type of initializer block is formally called an "instance initializer", because it is declared within the instance scope of the class -- "static initializers" are a related concept where the keyword static is placed before the brace that starts the block, and which is executed at the class level as soon as the classloader completes loading the class (specified at http://docs.oracle.com/javase/specs/jls/se5.0/html/classes.html#8.6) The initializer block can use any methods, fields and final variables available in the containing scope, but one has to be wary of the fact that initializers are run before constructors (but not before superclass constructors)
原文:http://www.cnblogs.com/neweracoding/p/4199192.html