Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Initializers vs Instance Initializers vs Constructors [duplicate]

I am studying for an exam about Java. While I was studying, I have encountered syntaxes in java which are unfamiliar to me. Such as a curly braces({}) unside a class body without a name, some has a static keyword. I have found out that they are called "Initializers". Can anyone help me point out key differences among them and how they differ from a Constructor. Thanks

like image 978
steven0529 Avatar asked Feb 21 '14 01:02

steven0529


2 Answers

The main difference between them is the order they are executed. To illustrate, I will explain them with an example:

public class SomeTest {

    static int staticVariable;
    int instanceVariable;        

    // Static initialization block:
    static {
        System.out.println("Static initialization.");
        staticVariable = 5;
    }

    // Instance initialization block:
    {
        System.out.println("Instance initialization.");
        instanceVariable = 10;
    }

    // Constructor
    public SomeTest() {
        System.out.println("Constructor executed.");
    }

    public static void main(String[] args) {
        new SomeTest();
        new SomeTest();
    }
}

The output will be:

Static initalization.
Instance initialization.
Constructor executed.
Instance initialization.
Constructor executed.

Briefly talking:

  • Static initialization blocks run once the class is loaded by the JVM.
  • Instance initialization blocks run before the constructor each time you instantiate an object.
  • Constructor (obviously) run each time you instantiate an object.
like image 180
Trein Avatar answered Nov 14 '22 06:11

Trein


A Constructor is called once when a new instance of a class is created. The values initialized in the constructor belong to the scope of the instance. Each Instance may have a different value for the same field initialized in the Constructor.

Static Initializers are useful for executing setup code in Static Classes and filling out data structures in Enums. They are called once, in order from top to bottom when the Class is loaded into the JVM and the data exists within the scope of the Class or Enum. All references to the Class will return the same value for fields initialized in the Static Initializers

Unnamed Curly Braces are Anonymous code blocks that scope reference names. If you create a reference inside the blocks, you can not get the value of that reference outside the block. If you find yourself needing them it's a sign you need to refactor your code into more methods.

like image 1
jeremyjjbrown Avatar answered Nov 14 '22 07:11

jeremyjjbrown