Page 1 of 1

[HD Pg 206, Sec. 8.5.1 - forward-referencing]

Posted: Wed Feb 13, 2019 8:23 pm
by OCAJO1

Code: Select all

Class A {

    String biz;

    {int test = 20; 
     String biz;
    }
    
    int test = 10;
}
No complier error! Although one test variable and one biz variable is within an instance initializer block and one is not, aren't they all same class' members?

Re: [HD Pg 206, Sec. 8.5.1 - forward-referencing]

Posted: Wed Feb 13, 2019 9:37 pm
by admin
No, the ones inside { } are not instance members. They are local to the { } block. This has nothing to do with forward referencing.

Re: [HD Pg 206, Sec. 8.5.1 - forward-referencing]

Posted: Thu Feb 14, 2019 1:33 pm
by OCAJO1
Aha. So the two in the block are on the stack, not on the heap. That clears it up. :thumbup:

Re: [HD Pg 206, Sec. 8.5.1 - forward-referencing]

Posted: Thu May 16, 2019 10:58 am
by Username987654
Could you please provide any additional guidance on why the last TestClass example in this section compiles and prints? I did verify that it compiles and runs. Without having done so, I would have thought that it is essentially a redirection/remix (if you will) of the invalid forward reference. Since printI() is called from inside the instance initiailizer, why don't the "normal" instance initiailizer rules apply here (since the "scope" is instance initiailizer)? I guess the rules of the instance method supercede the rules of the instance initiailizer? Thanks in advance for attempting to clear up my blind spot.

Re: [HD Pg 206, Sec. 8.5.1 - forward-referencing]

Posted: Thu May 16, 2019 9:44 pm
by admin
There is nothing special here other than that is how the language designers designed the rule. Forward referencing a variable is not allowed by accessing a variable through a method is allowed. Prohibiting access to a variable from a method cannot be done because the method has no knowledge of when it has been invoked. And prohibiting a call to a method from an instance initializer seems like a big restriction. So, I guess, they had no choice but to allow a method to access a "default" pre-initialization value of a variable through a method from an instance initializer.

Re: [HD Pg 206, Sec. 8.5.1 - forward-referencing]

Posted: Thu May 16, 2019 11:05 pm
by Username987654
Thank you!