Clarification in Java basics - Constructors and "static"?
Asked Answered
C

4

12
class test
{
    test() {
        System.out.println("Constructor");
    }

    { System.out.println("Hai"); }
}


public class sample
{
    public static void main(String [] a) {
        test t = new test();        
    }
}

In the above code, why is "Hai" printed before the test() constructor is called?

The test() constructor in the test class is above the "Hai" statement and should be called first, right?

Coact answered 12/12, 2009 at 12:31 Comment(0)
G
36

Let express with a more clear example:

public class Test {

    static {
         System.out.println("static initializer");
    }

    {
         System.out.println("instance initializer");
    }

    public Test() {
         System.out.println("constructor");
    }

}

and test it as follows:

public class Main {

    public static void main(String[] args) {
        Test test1 = new Test();
        Test test2 = new Test();
    }

}

output:

static initializer
instance initializer
constructor
instance initializer
constructor

The static initializers are executed only once during runtime, specifically during loading of the class. The instance initializers are executed during every instantiation before the constructor.

You can have more than one of them and they will be executed in the order as they appear in the coding.

The major benefit of instance initializers is that they are executed regardless of which constructor you use. They applies on each of them so that you don't need to duplicate common initialization over all of them.

The major benefit of static initializers is that they are executed only once during class loading. A well known real world example is the JDBC driver. When you do

 Class.forName("com.example.jdbc.Driver");

which only executes the static initializers, then any (decent) JDBC driver will register itself in the DriverManager as follows

 static {
      DriverManager.registerDriver(new com.example.jdbc.Driver());
 }

this way the DriverManager can find the right JDBC driver during getConnection().

Gabo answered 12/12, 2009 at 12:50 Comment(0)
P
7

Yes. It's an instance initializer. It's run as soon as the class is instantiated.

Profuse answered 12/12, 2009 at 12:33 Comment(5)
So the static keyword is optional?Penninite
so if create a static block in the above code, which will run first the static block or the static initializer block?....can u explain what is static initializer?Coact
It is definitely NOT a static initializer.Gabo
Oops, you're right, it's not static at all, it's an instance initalizer. Fixed.Profuse
Because there are many who doesn't understand it and/or because one with 10K+ reps "must" be correct.Gabo
B
3

In the above code why is that the statement given within the braces ((i.e) "Hai") is Printed before the constructor is executed.

Because this is the expected behavior as described in the section 12.5 Creation of New Class Instances of the Java Language Specification :)

Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object using the following procedure:

  1. Assign the arguments for the constructor to newly created parameter variables for this constructor invocation.
  2. If this constructor begins with an explicit constructor invocation of another constructor in the same class (using this), then evaluate the arguments and process that constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason; otherwise, continue with step 5.
  3. This constructor does not begin with an explicit constructor invocation of another constructor in the same class (using this). If this constructor is for a class other than Object, then this constructor will begin with an explicit or implicit invocation of a superclass constructor (using super). Evaluate the arguments and process that superclass constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, continue with step 4.
  4. Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception. Otherwise, continue with step 5. (In some early implementations, the compiler incorrectly omitted the code to initialize a field if the field initializer expression was a constant expression whose value was equal to the default initialization value for its type.)
  5. Execute the rest of the body of this constructor. If that execution completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, this procedure completes normally.

See section 8.6 Instance Initializers for more details on... instance initializers.

Bargeman answered 12/12, 2009 at 23:44 Comment(0)
V
2

Braces immediately within a class introduces an instance initialiser (introduced in Java 1.1). They are treated much the same as code to assign fields written as part of the declaration. So the following are equivalent:

 private final Thing x = new Thing();

and

 private final Thing x;
 {
     x = new Thing();
 }

The code is executed by constructors immediately after calling a super constructor. So, assuming no other initialisation, the code can be written equivalently as part of the constructor:

 private final Thing x;
 public MyCLass() {
     super(); // Often implicit.
     x = new Thing();
 }

Braces in the same position preceded by the static keyword and static initialisers, executed once when a class is initialised, not on a per-instance basis.

Veronica answered 12/12, 2009 at 12:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.