Re: Initializing variable style question
- From: Lew <lew@xxxxxxxxxxxxx>
- Date: Thu, 13 Nov 2008 09:26:31 -0800 (PST)
On Nov 13, 12:13 pm, Nicros <bcc...@xxxxxxxxx> wrote:
On Nov 13, 9:10 am, Nicros <bcc...@xxxxxxxxx> wrote:
Between:
public class MyClass
{
I have to say, using groups through google SUX.
The question is, between
public class MyClass
{
int x = 0;
public MyClass ()
{
}
}
and
public class MyClass
{
int x;
public MyClass()
{
x = 0;
}
}
Is there a valid reason to initialize stuff in the constructor only?
Is it a style only thing?
Don't use either - initialize a variable to its "zero-like" value
(zero or null) is redundant either way. It forces the variable to
that value twice, once when the member is constructed and again when
the initializer or constructor is executed.
public class MyExample
{
int x;
}
will do the job.
To initialize to a non-zero-like value, either way will do. I prefer
initializers, because it puts the initialization together with the
declaration, but others prefer to use the constructor. Sometimes it
makes a difference - if you need to initialize a variable to the same
value for many constructors, put it in the declaration. If you need
to initialize it to a different value depending on the constructor, it
must go in the constructor. 'final' variables can and must be
initialized exactly once, so that usually determines where you put
it. 'final' instance variables must be explicitly initialized even to
a zero-like value. Constants should be initialized in the
declaration.
public class MyExample
{
private static final int LENGTH = 16;
private final String names [] = new String [LENGTH];
private boolean ready;
private String foo;
public MyExample()
{
this.foo = "";
}
public MyExample( String firstFoo )
{
this.foo = firstFoo;
}
// etc.
}
--
Lew
.
- Follow-Ups:
- Re: Initializing variable style question
- From: Philipp
- Re: Initializing variable style question
- References:
- Initializing variable style question
- From: Nicros
- Re: Initializing variable style question
- From: Nicros
- Initializing variable style question
- Prev by Date: opensource CA server
- Next by Date: Re: Check Security Header SOAP Message
- Previous by thread: Re: Initializing variable style question
- Next by thread: Re: Initializing variable style question
- Index(es):
Relevant Pages
|