Search code examples
javafinal

When is it appropriate to use blank final variables?


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?


Solution

  • 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.