Initialization Blocks
- Initialization blocks are the third place (other than methods and constructors) in a Java program where operations can be performed.
- They don't have names, they can't take arguments, and they don't return anything.
- A static initialization block runs once, when the class is first loaded.
- An instance initialization block runs once every time a new instance is created.
- Instance initialization block code runs right after the class to super() in a constructor and before the constructor's code has run.
- When it's time for initialization blocks to run, if a class has more than one, they will run in the order in which they appear in the class file.
- Instance init blocks are often used as a place to put code that all the constructors in a class should share.
- If we make a mistake in our static init blocks, the JVM can throw an exception.
class A {
A() {
super();
System.out.println("4. A's Constructor");
}
static {
System.out.println("1. A's Static Init Block");
}
{
System.out.println("3. A's Instance Init Block");
}
}
class ShellClass extends A {
ShellClass() {
super();
System.out.println("7. ShellClass's Constructor");
}
{
System.out.println("5. ShellClass's 1st Instance Init Block");
}
static {
System.out.println("2. ShellClass's Static Init Block");
}
{
System.out.println("6. ShellClass's 2nd Instance Init Block");
}
public static void main(String[] args) {
new ShellClass();
System.out.println("\nCreating Another Instance of ShellClass...\n");
new ShellClass();
}
class ShellClass {
static int x[] = new int[4];
static {
x[4] = 5;
}
public static void main(String[] args) {
new ShellClass();
}
Comments
Post a Comment