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

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

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

Post 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?

admin
Site Admin
Posts: 10058
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post by admin »

No, the ones inside { } are not instance members. They are local to the { } block. This has nothing to do with forward referencing.
If you like our products and services, please help us by posting your review here.

OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

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

Post by OCAJO1 »

Aha. So the two in the block are on the stack, not on the heap. That clears it up. :thumbup:

Username987654
Posts: 95
Joined: Sat Dec 26, 2015 6:37 pm
Contact:

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

Post 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.

admin
Site Admin
Posts: 10058
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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.
If you like our products and services, please help us by posting your review here.

Username987654
Posts: 95
Joined: Sat Dec 26, 2015 6:37 pm
Contact:

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

Post by Username987654 »

Thank you!

Post Reply

Who is online

Users browsing this forum: No registered users and 103 guests