I come from C++ background, where the field of a class are initialized inside the constructor. But here is java I see that I can initialize then while declaring, which is different from C++.
So, I my question was which is the best/traditional practice to initialize the field members of any class. Is it…
-
at the time to declaring?
class testClass
{
private int x = 100;
} -
using non-static scope?
class testClass{
private int x;
{
x = 100;
}
} -
or inside of a constructor?
class testClass{
private int x;
testClass(){x = 100;}
}
( Because I of my background I am a little biased towards initializing field members inside of a constructor.)
I don’t think there is a ‘best practice’ for initializing member variables. Obviously in Java you can initialize them in the declaration which is fine, or you can do it from the constructor. Unless you need to do something complicated (i.e. obtain a reference to a DataSource or something like that which might only be available with arguments passed in to the constructor).
In other words, there isn’t a ‘right way’ of doing it, consistency is probably more important.
That said, bear in mind that Java will initialise uninitialised member variables for you if you don’t do it. e.g.
intvariables will be set to 0,booleanvariables will be set to false, any objects will be set to null, etc.