2

Lets say I have a Java class, like this:

public class Example {
    private Foo foo = new Foo();
    private Bar bar = new Bar(this.foo);
}

Is it guaranteed that bar will always be instantiated with a Foo as its constructor, or is there a chance it will be instantiated with null instead?

Is the order in which the members of a Java class are intialized guaranteed?

midrare
  • 2,371
  • 28
  • 48
  • 1
    Does this answer your question? [Java order of Initialization and Instantiation](https://stackoverflow.com/questions/23093470/java-order-of-initialization-and-instantiation) – Progman Mar 13 '21 at 17:57

1 Answers1

2

Yes, it's guaranteed.

In particular, JLS 12.5 Creation of New Class Instances says (emphasis added):

  1. 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.
Andy Turner
  • 137,514
  • 11
  • 162
  • 243