Initialize member variables in the beginning of class definition or in constructor?

In your example, the only difference is when they are initialized. According to the JLS, instance variables are initialized before the constructor is called. This can become interesting when you have super classes to deal with, as the initialization order isn't always so obvious. With that, keep in mind "super" instance variables will still be initialized when no explicit super constructor is called.


The difference is the order in which they are initialized / set.

Your class member variables will be declared / set before your constructor is called. My personal preference is to set them in the constructor.


In-class initialization allows you to avoid writing a trivial constructor.

You have to initialize instance members that depend on constructor parameters inside the constructor. It could be reasonable, for readability if nothing else, to put initialization of all other instance members inside the same constructor.

Otherwise, there's no difference.

Tags:

Java