什么时候使用空白的最终变量? [英] When is it appropriate to use blank final variables?

查看:140
本文介绍了什么时候使用空白的最终变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找另一个问题关于最终变量并注意到您可以在不初始化变量的情况下声明最终变量(空白最终的变量)。有没有理由这样做,什么时候有利?

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是不可变的(一旦创建,就无法改变因为颜色是最终的)。
但你仍然可以通过用各种颜色构建它们来创建各种Bla。

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.

参见这个问题例如。

编辑

也许值得补充的是,空白决赛在Java中具有非常特殊的含义,这似乎在评论中引起了一些混淆 - 参见 Java语言规范4.12.4

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:


空白的final是一个最终变量,其声明缺少初始值。

A blank final is a final variable whose declaration lacks an initializer.

你然后必须在构造函数中分配该空白的最终变量。

You then must assign that blank final variable in a constructor.

这篇关于什么时候使用空白的最终变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆