0
I’m studying for certification.
The book says that the declaration order of attributes and initialization blocks should be considered.
Scenario #1: while doing so:
public class Teste {
{
System.out.println("Bloco: " + val);
}
private int val = 1;
public int getVal() {
return val;
}
public static void main(String[] args) {
System.out.println("Val: " + new Teste().getVal());
}
}
The program does not compile and displays the error: illegal forward reference
.
Scenario #2: while doing so:
public class Teste {
{
val = 2;
}
private int val = 1;
public int getVal() {
return val;
}
public static void main(String[] args) {
System.out.println("Val: " + new Teste().getVal());
}
}
The program compiles and when running prints Val: 1
.
Why can’t I reference the variable val
but I can assign a value to her?
Also, if I was able to assign this value, why is the printed value different from the assigned?
Related (or duplicate): https://answall.com/a/118779/28595
– user28595
@Articuno edited the question to leave a little more focused on the doubt itself.
– igventurelli