The first method gives you custom control over how to initialize the class object that you are dealing with each constructor, while the second parameter will initialize the Family object in the same way for all constructors.
The first method is preferable because it allows you to take the Family object into your constructor, allowing you to do things like dependency injection, which is usually good programming practice (and makes testing easier).
In addition, both of them are member variables (not static, as someone else said, for this you need to use a static keyword). Each instance of this class will contain an instance of the Family object in this way.
I would recommend something like this
public class Person { public Person(Family family) { this.family = family; } Family family; }
Edit: To respond to the comment that was made about my post (which was accurate, somewhat), there is a difference in which the order of the objects is initialized. However, the comment said that the order of work:
initialization of instance variables -> instance initializer -> constructor
From checking this, it seems that it depends on what happens first in the code, the initialization of the instance variables or instance initializers, and after which the constructor is called after both of them . Consider an example where the constructor of the Family object simply prints the string specified by it:
public class Person { { Family familyB = new Family("b"); } Family familyA = new Family("a"); Family familyC; public Person() { this.familyC = new Family("c"); } }
leads to this result when building the person object:
Family: b
Family: a
Family: c
but this code:
public class Person { Family familyA = new Family("a"); { Family familyB = new Family("b"); } Family familyC; public Person() { this.familyC = new Family("c"); } }
leads to this result when building the person object:
Family: a
Family: b
Family: c