There's a very simple program:
public class A {
public static void main(String[] p) {
final Runnable r = new Runnable() {
public void run() {
System.out.println(r);
}
};
r.run();
}
}
And this gives:
$ javac A.java
A.java:6: variable r might not have been initialized
System.out.println(r);
^
1 error
(In the real code, there is one more level (a listener), and referencing via this
does not work)
Should we declare a local variable without an initial value, we get an error. This error occurs only for local variables since Java automatically initializes the instance variables at compile time (it sets 0 for integers, false for boolean, etc.).
If the programmer, by mistake, did not initialize a local variable and it takes a default value, then the output could be some unexpected value. So in case of local variables, the compiler will ask the programmer to initialize it with some value before they access the variable to avoid the usage of undefined values.
To initialize a variable is to give it a correct initial value. It's so important to do this that Java either initializes a variable for you, or it indicates an error has occurred, telling you to initialize a variable.
In this case, you can use "this" to avoid the compilation error:
final Runnable r = new Runnable() {
public void run() {
System.out.println(this); // Avoid compilation error by using this
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With