Re: Initializer vs. Constructor assignment
- From: "SPG" <steve.goodsell@xxxxxxxxxxxxxxxxxxxxxx>
- Date: Sat, 07 May 2005 17:01:29 GMT
"Matthias Kaeppler" <nospam@xxxxxxxxxxxxxxx> wrote in message
news:d5iljv$qav$03$1@xxxxxxxxxxxxxxxxxxxx
> Hello,
>
> I am currently reading "Java in a Nutshell" 5th Edition (O'Reilly) and
> some questions arose concerning the proper use of Field
> Defaults/Initializers and Constructors.
>
> It is stated that "The initialization code is inserted into a constructor
> in the order in which it appears in the source code [...]".
>
> Does that means that this code:
>
> class A {
> int a = 5;
> }
>
> is equivalent to:
>
> class A {
> int a;
> A() {
> a = 5;
> }
> }
>
> or does the second code snippet first initialize a with 0 and then assigns
> 5 when the ctor body is entered?
>
> Or does all this initialization stuff boil down to be merely a matter of
> style? Or are instance initializers and field defaults only thought to be
> a means for initializing anonymous classes and not to be used in other
> circumstances?
> If not, are there any guidelines when I should initialize a class member
> in the class body vs. the ctor body?
>
> --
> Matthias Kaeppler
Hi,
If you compile then decompile your code, you'll find that your variables are
put into the constructor and set in there.
You should also notice that if you have multiple constructors then the same
initialisation is done in each, hence potentially bloating the class file
uneccessarily.
one way to reduce this is to always initialize your vars inside one
constructor, and in each additional constructor simply call the default
constructor first..
example:
Source code:
public class Sample {
int a = 1;
int b = 2;
int c = 3;
public Sample() {
}
public Sample(int d) {
}
}
Decompiled:
public class Sample
{
int a;
int b;
int c;
public Sample()
{
a = 1;
b = 2;
c = 3;
}
public Sample(int d)
{
a = 1;
b = 2;
c = 3;
}
}
Using default constructor....
Source:
public class Sample {
int a;
int b;
int c;
public Sample() {
a=1;
b=2;
c=3;
}
public Sample(int d) {
this();
}
}
Decompiled:
public class Sample
{
int a;
int b;
int c;
public Sample()
{
a = 1;
b = 2;
c = 3;
}
public Sample(int d)
{
this();
}
}
As you can see, if you have many constructors and many variables, you could
indeed have a rather bloated compiled class.
Hope this helps,
Steve
.
- References:
- Initializer vs. Constructor assignment
- From: Matthias Kaeppler
- Initializer vs. Constructor assignment
- Prev by Date: Re: Java consultant: Are we being conned? Please help!
- Next by Date: Re: Hi I have one web application and i want to get the number of users who are currently accessing the application. Also I want to get the user details of each user, which is stored in a database. How can I do this? Pls help. Getting No: and
- Previous by thread: Initializer vs. Constructor assignment
- Next by thread: Re: Initializer vs. Constructor assignment
- Index(es):
Relevant Pages
|