Reputation: 25
I'm new to Java but experienced in C++. I came across some code that I didn't understand:
public class SomeClass {
private SomeOtherClass someOther = new SomeOtherClass();
private AThirdClass thirdClass;
SomeClass() {
this.thirdClass = new AThirdClass();
}
}
Why when there is only a single constructor would you have someOther initialized in the initialization and thirdClass initialized in the constructor?
Upvotes: 1
Views: 100
Reputation: 4593
There's nothing in your example that would suggest a reason, but underlying implementations may have problematic and poorly-considered code to consider. It may be important for you to know that the initialization of SomeOtherClass
in your example will always run before the initialization in the constructor. Someone may have thought that was important.
Or, it could simply be two different developers with two different style preferences. Neither is technically wrong, but both have their (dis)advantages.
Upvotes: 0
Reputation: 10891
The below is one reason you may wish to do that.
public class SomeClass {
private SomeOtherClass someOther = new SomeOtherClass();
private AThirdClass thirdClass;
SomeClass( int x ) {
this.thirdClass = new AThirdClass( x );
}
}
But that only explains why you would want to initialize thirdClass in the constructor. I am at a loss to explain why you would want to initialize someOther in the init block.
Upvotes: 1
Reputation: 9359
There is absolutely no reason, unless you get into static declarations, in which case it could make some sense.
Upvotes: 0