1

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?

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

There is absolutely no reason, unless you get into static declarations, in which case it could make some sense.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.