I was looking at another question about final variables and noticed that you can declare final variables without initializing them (a blank final variable). Is there a reason it is desirable to do this, and when is it advantageous?
This is useful to create immutable objects:
public class Bla {
private final Color color;
public Bla(Color c) {this.color = c};
}
Bla is immutable (once created, it can't change because color is final). But you can still create various Blas by constructing them with various colors.
See also this question for example.
EDIT
Maybe worth adding that a "blank final" has a very specific meaning in Java, which seems to have created some confusion in the comments - cf the Java Language Specification 4.12.4:
A blank final is a final variable whose declaration lacks an initializer.
You then must assign that blank final variable in a constructor.
The final property of class must have a value assigned before object is created. So the last point where you can assign value to them is constructor.
This is used often for immutable objects.
public class Foo {
private final Bar bar;
public Foo(Bar bar) {
this.bar = bar;
}
public Bar getBar() {
return new Bar(bar);
}
}
What wiki says about it
Defensive copying.
You can do this when you do not known what the value will be prior to the instrumentation of a Object, it just needs to have a value assigned in its constructor.
This is how you make immutable objects and it is used in the builder pattern.
class Builder{
final BuilderContext context;
private Builder(BuilderContext context){
this.context=context;
}
public static Builder New(){
return new Builder(new BuilderContext());
}
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