Why is the following code possible? (Just an example I just came up with while working on other code)
public String getLogIdentifierFromFile(final File file) {
//this.file = null; //Gives compiler error as obviously expected
nullify(file);
return "";
}
public void nullify(Object object) {
object = null;
}
And how can I ensure that the final
from the top function actually has an effect? This time it is me making the nullify
method, but it can also be anyone's code that my method needs to call.
Yes! You can initialize a blank final variable in constructor or instance initialization block.
1) Java final variable If you make any variable as final, you cannot change the value of final variable(It will be constant).
If you prefix a class definition with final , you prevent anyone from subclassing that class. Value types don't support inheritance so it doesn't make sense to mark a struct or enum as final . The final keyword communicates to the compiler that the class cannot and should not be subclassed.
Final variables If a variable is declared with the final keyword, its value cannot be changed once initialized.
The code doesn't do what you think it does.
final
applies to the reference. Your code nulls out a non-final
copy of the original final
reference. The copy is taken when you call nullify()
.
If you examine file
after calling nullify()
, you will observe that it remains unchanged.
Thus, this isn't a loophole in how final
works.
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