I'm studying for certification.
The book says that the declaration order of attributes and initialization blocks should be considered.
Scenario # 1: while doing this:
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 this:
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 runs Val: 1
.
Why can not I reference the variable val
but can I assign a value to it?
In addition, if I was able to assign this value, why is the printed value different from the one assigned?