Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of non-static block in java? [duplicate]

Tags:

java

Possible Duplicate:
How is an instance initializer different from a constructor?

When all the required work can be done inside the constructor, then why do we still need non-static block in Java?

EDIT: What about normal classes for which non-static blocks run everytime before the constructor?

like image 463
Ashwyn Avatar asked Aug 08 '12 17:08

Ashwyn


1 Answers

In additional to @Bohemian's answer.

If you have multiple constructors an intialiser block avoid duplication.

public class A {
     final Map<String, String> map = new HashMap<String, String>(); {
        // put things in map.
     }
     final int number; {
        int number;
        try {
            number = throwsAnException();
        } catch (Exception e) {
            number = 5;
        }
        this.number = number;
     }

     public A() { /* constructor 1 */ }
     public A(int i) { /* constructor 2 */ }
}

What about normal classes for which non-static blocks run everytime before the constructor?

Technically the order is

  • the super constructor is always called first
  • all the initializer blocks in order of appearence.
  • the constructor code

In reality all this code is in the byte code for each constructor so there is nothing before or after the constructor at runtime.


Before there is any more confusion as to the order of initialization

public class Main extends SuperClass {
    {
        System.out.println("Initialiser block before constructor");
    }

    Main() {
        System.out.println("Main constructor");
    }

    {
        System.out.println("Initialiser block after constructor");

    }

    public static void main(String... args) {
        new Main() {{
            System.out.println("Anonymous initalizer block");
        }};
    }
}

class SuperClass {
    SuperClass() {
        System.out.println("SuperClass constructor");
    }
}

prints

SuperClass constructor
Initialiser block before constructor
Initialiser block after constructor
Main constructor
Anonymous initalizer block
like image 67
Peter Lawrey Avatar answered Oct 02 '22 16:10

Peter Lawrey