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