FAQ
overflow

Great Answers to
Questions About Everything

QUESTION

When setting initial values for class members we have the option of setting them in the declaration

public class MyClass {
    public int someInt = 300;
    // etc. etc.
}

or within the constructor

public class MyClass {
    public int someInt;

    public MyClass() {
        someInt = 300;
    }
}

Which of these is considered better practice? Are there any performance differences between the two?

{ asked by Mike C }

ANSWER

You could assign primitives in the class declaration.

But, if you're assigning classes to members you should do in the constructor.
Think about a situation where you're trying to assign some class, but its constructor fails throws an exception:

public class MyClass {
    public SomeOtherClass member1 = new SomeOtherClass();
}

The exception will be thrown in the class creation, and if you have a lot of members it gets hard to debug (You can't place a breakpoint if it's not in the constructor)

But if you assign them in the constructor you can manage the exceptions, catch them, or at least put a breakpoint.

{ answered by Yochai Timmer }
Tweet