Page 1 of 1
About Question enthuware.ocpjp.v7.2.1466 :
Posted: Fri Apr 01, 2016 10:59 am
by doziransky
So I'm having trouble understand why this works:
System.out.println(C.this.c);
I thought that since C is still being constructed (as we're in the constructor) the value of c would be null and only become 'c' after the constructor has finished running.
I tried writing this code and it's clear that c does in fact contain the value 'c' before the constructor finishes running, but why is this the case?
How does C have instance variable values before it actually exists?
Thanks for your help.
Re: About Question enthuware.ocpjp.v7.2.1466 :
Posted: Fri Apr 01, 2016 11:24 am
by admin
You should remember that all instance fields get their default values first, even before the constructor runs. These default values are 0 for numeric types, false for boolean, and null for reference types.
This is done by the JVM itself when it allocates memory for the object. It cleans the memory locations of these fields and then gives the control to the instance initializers and then the constructor so that they can initialize the value of these fields as per the business logic.
That is why, the field has a value even before the constructor is finished.
BTW, why do you think that c would be null? Primitives types can never be null. They are not references. They are primitives. They don't point to anything. They just have a value, which is 0 to begin with (or false for boolean.)
Re: About Question enthuware.ocpjp.v7.2.1466 :
Posted: Fri Apr 01, 2016 3:34 pm
by doziransky
Oh woops yea I meant the default value, not null. Was thinking from an object perspective.
And okay cool I had no idea it worked like that, thanks!
Re: About Question enthuware.ocpjp.v7.2.1466 :
Posted: Mon Aug 13, 2018 2:24 pm
by vahankh
Why
prints
a instead of
b?
Isn't B already constructed?
Re: About Question enthuware.ocpjp.v7.2.1466 :
Posted: Mon Aug 13, 2018 8:23 pm
by admin
Because B.this.c refers to the "char c = 'a'" definition in class B. This c is not being modified anywhere.
Re: About Question enthuware.ocpjp.v7.2.1466 :
Posted: Mon Aug 13, 2018 8:49 pm
by vahankh
admin wrote: ↑Mon Aug 13, 2018 8:23 pm
Because B.this.c refers to the "char c = 'a'" definition in class B. This c is not being modified anywhere.
Thanks. But what about the following constructor?
Doesn't it change the value of 'a'?
Re: About Question enthuware.ocpjp.v7.2.1466 :
Posted: Mon Aug 13, 2018 8:55 pm
by admin
What do you mean by changing the value of 'a'? 'a' is a value. c is the variable that can be changed. However, why do you think super('b') changes the instance variable c of class B?
Re: About Question enthuware.ocpjp.v7.2.1466 :
Posted: Tue Aug 14, 2018 9:55 am
by vahankh
When parent constructor is called
Doesn't
this refer to object B?
Re: About Question enthuware.ocpjp.v7.2.1466 :
Posted: Tue Aug 14, 2018 8:10 pm
by admin
No, it refers to A's c.