Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it appropriate to use blank final variables?

Tags:

java

final

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?

like image 930
Rob Volgman Avatar asked Jul 05 '12 13:07

Rob Volgman


3 Answers

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.

like image 123
assylias Avatar answered Oct 13 '22 19:10

assylias


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.

like image 5
Damian Leszczyński - Vash Avatar answered Oct 13 '22 18:10

Damian Leszczyński - Vash


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());
    }
like image 2
John Kane Avatar answered Oct 13 '22 18:10

John Kane