-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Either approach is fine if you have just one constructor.
If however you have more than one, I would initialise the field in the
class declaration rather than the constructor:
class Thing
{
private int field = 42;
// default ctor
public Thing()
{
...
}
// other ctors
public Thing( ... ) { ... }
}
This means that the value is initialised correctly for all
constructors, reducing the chances of a ****-up.
Someone already explained why initialization on declaration is deceptive and
thus a bad practice.
Whenever possible (because there may be *special* cases where this is not
possible or desireable), use initialization in the *default* constructor. For
classes with multiple constructors, use chaining:
public class LifeUniverseAndEverythingElse
{
private int m_answer;
public LifeUniverseAndEverythingElse()
{
m_answer = 42;
}
public LifeUniverseAndEverythingElse(String p_greeting)
{
this();
System.out.println(p_greeting + ", Arthur!");
}
public LifeUniverseAndEverythingElse(Object p_something)
{
this();
System.out.println("Talking doors are made of [" +
p_something.getClass().getName() + "]");
}
}
- --
Emir.
"Politicians, like diapers, have to be changed frequently.
And for the very same reason." -- Anonymous
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (MingW32)
iD8DBQFACBISuSy542G+Z7QRAnr0AJ9SRIJzDd84tlL7H0ytCV6Yp6e9AQCgkpej
4upvaj0HoiG3WsKqugMlfjw=
=CKjy
-----END PGP SIGNATURE-----