I'd want to use Java 9's try-with-resources capability by putting a reference variable in try with resources rather than the variable's full declaration. I also realise that in order to do so, I must adhere to the following rule: the variables used as try-with-resources resources must be final or nearly so. I'll begin with a local variable and then progress to an instance variable.
Variable at the local level:
-I create a final variable that follows the specified rule and builds correctly:
Java: public static void main (String[] args) throws IOException{ final FileWriter fw = new FileWriter ("test.txt"); try(fw) { //some code } }
-If I additionally removed the final keyword, it would be recompiled because fw is basically treated as a final variable that is only initialised once and never transmitted.
Java: public static void main (String[] args) throws IOException{ FileWriter fw = new FileWriter ("test.txt"); try(fw) { //some code } }
Variable example:
Will this paradigm, however, work for the instance variable? Let's give it a go.
- Let's start with the last instance variable, which follows the rule and builds correctly:
public class Test { final FileWriter fw = new FileWriter ("a.txt"); void m1() throws IOException { try(fw ) { //some code } } }
-Should it compile again if I remove the final keyword? This should be the final workforce because I am not modifying fw anywhere but simply initialising it once. Unfortunately, this is not going to work:
public class Test { FileWriter fileWriter = new FileWriter ("a.txt"); void m1() throws IOException { try(fileWriter) { //some code } } }
This sends me a message: the variable used as a test resource with resources must be final or genuinely final. So, after all of that, I return to my original question. Is it possible for an instance variable to be effectively final, or is this phrase reserved for local variables? As I've just demonstrated, I never alter a variable following this post (which should be deemed essentially final), yet the compiler never views it as such.