zer0stimulus
zer0stimulus

Reputation: 23606

Java: Is member initialization outside of constructor always guaranteed to be invoked?

If I initialize a member variable outside of a constructor, when does the member actually get initialized? Is it guaranteed to be initialized for all possible constructors of the class?

public class MyClass
{
    private String myName = "MyClass";

    public MyClass(int constructor1Arg)
    {}

    public MyClass(int constructor2Arg1, int constructor2Arg2)
    {}
}

Upvotes: 4

Views: 2593

Answers (3)

user330315
user330315

Reputation:

According to the Java Language Specification:

http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.5

the instance variables are initialized before the constructor is called unless any previous initialization throws an error:

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.

(Step 5 is running the constructor)

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500535

Yes. All instance variable initializers are executed after superconstructor has executed, but before the body of any constructor declared in this class.

(As Jigar Joshi mentions, this is assuming the superconstructor executes normally.)

Upvotes: 15

Jigar Joshi
Jigar Joshi

Reputation: 240900

Yes, if there is no exception while creation of object

Upvotes: 3

Related Questions