When is it appropriate to use blank final variables?

前端 未结 9 1386
野趣味
野趣味 2020-12-16 00:24

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 reaso

相关标签:
9条回答
  • 2020-12-16 01:18

    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.

    0 讨论(0)
  • 2020-12-16 01:20

    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());
        }
    
    0 讨论(0)
  • 2020-12-16 01:20

    I find them very useful for methods that derive a state. It provides a clean execution path and makes sure the state variable is assigned once and only once. For example:

    public boolean isEdible() {
        final boolean edible;
    
        if (vegetable) {
            edible = true;
        } else if (animal) {
            if (vegetarian) {
                edible = false;
            } else {
                edible = true;
            } 
        }
        System.out.println("Is edible: " + edible);
        return edible;
    }
    
    0 讨论(0)
提交回复
热议问题