Java – when is it appropriate to use blank final variables?

I'm looking at another question about final variables and notice that you can declare final variables without initializing them (a blank final variable) Is there any reason to do so and when is it advantageous?

Solution

This is useful for creating immutable objects:

public class Bla {
    private final Color color;

    public Bla(Color c) {this.color = c};

}

BLA is unchanged (once created, it cannot be changed because the color is final) However, you can still create various Blas by building various Blas with various colors

See also this question, for example

edit

It may be worth mentioning that the "blank final" has a very specific meaning in Java and seems to have caused some confusion in the comments - see Java language specification 4.12 4:

Then, you must allocate a blank final variable in the constructor

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>