The blog of Jafar Aliyev

Archive

Creation date:

Static and instance initilization blocks

Static initialization blocks run when the class is first loaded. An instance initialization blocks run when the instance is created. An initializastion blocks run in the order in which they appear in the class file (from the top down). Instance initializer block runs after the call to super() in a constructor. Based on these rules we can demonstrate it in the following code:

class A {
  static {
    System.out.println("static block of A");
  }
  {
    System.out.println("instance block of A");
  }
  public A() {
    System.out.println("constructor of A");
  }
}

class B extends A {
  static {
    System.out.println("static block 1 of B");
  }
  {
    System.out.println("instance block 1 of B");
  }
  static {
    System.out.println("static block 2 of B");
  }
  {
    System.out.println("instance block 2 of B");
  }
  public B() {
    System.out.println("constructor of B");
  }
  public static void main(String[] args) {
    new B();
  }
}

If we run this code we'll get the following output:

static block of A
static block 1 of B
static block 2 of B
instance block of A
constructor of A
instance block 1 of B
instance block 2 of B
constructor of B

As we said the static blocks run once, when the class is first loaded. But when we run new B(), Java first calls the constructor of the super class(class A). Before running the constructor of class A, Java calls the constructor of Object class. Then it calls the instance initializing block of A and prints instance block of A. Then it runs constructor method of A. After this call, the instance initializer blocks are called in their creation order. Although one of static initializer block is between two instance initializer blocks, JVM ignores it during objet instantiaation as well as it ignores object initializer blocks during class loading time.

Author: Jafar N.Aliyev (Jsoft)

Read also

Use instanceof carefully
Usage of 'instanceof' method in some situations will give you a compilation error

Wrapper objects

Overloading

Java access and nonaccess modifiers
Look at this cheat sheet for Java access and nonaccess modifiers

Implicit typecasting

Protected details

Interface methods are always public

Static methods can not be overriden
Here I explain, why static methods can not be overriden

Implicit typecasting

Java Tips

Variable hiding

Postfix operators

Tricky Polymorphism

Pattern Matching

Default values

String equality

© Copyright

All articles in this site are written by Jafar N.Aliyev. Reproducing of any article must be followed by the author name and link to the site of origin(this site). This site also keeps the same rules relative to the articles of other authors.