Java - 最终变量 [英] Java - final variables

查看:100
本文介绍了Java - 最终变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道一旦最终变量赋值给它,就无法改变。但是我对此有几个问题:

I know that once a final variable has a value assigned to it, it cannot be changed. However I just have a couple of questions regarding this:


  • 当我有一个字段时,说 static最后的JButton按钮; 在一个类之外,然后在 main 方法中,尝试为它赋值, button =新JButton(OK); ,我收到错误告诉我删除最终修饰符?但是,由于原来的按钮变量尚未引用一个对象,因此我可以将其分配一次?

  • When I have a field, say static final JButton button; outside a class, and then in the main method, try to assign it a value, button = new JButton("OK");, I get an error telling me to remove the final modifier? However since the original button variable does not yet reference an object I was under the impression I could assign it once?

其次,如果我完全删除对按钮的引用,那么我只有静态最终JButton按钮; 外该类,我的IDE声称空白的最终字段按钮可能尚未初始化。这是否意味着所有最终字段 必须 被初始化?如果是这样,他们必须在那里进行初始化,然后我似乎无法在以后初始化它。

Secondly, if I completely remove reference to the button so I just have static final JButton button; outside the class, my IDE claims "The blank final field button may not have been initialised." Does this mean that all final fields must be initialised? And if so, must they be initialised there and then as I can't seem to initialise it later.

另外,愚蠢的问题,但我最初的假设是当一个最终变量被引用到一个实例或数据类型时,它无法分配给其他任何东西都是正确的,对吗?

Also, silly question, but my initial assumption that when a final variable is referenced to an instance or data type it can not be assigned to anything else is correct, right?

此代码不完整,但用于说明我的观点:

This code is not complete but is provided to illustrate my point:

public class FinalVarTester {

    static final JButton button;

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        Container container = frame.getContentPane();
        container.setLayout(new BorderLayout());
        button = new JButton("OK");
        container.add(button, BorderLayout.SOUTH);
    }

}


推荐答案

您应该在静态初始化程序中或直接初始化静态最终变量。所以要么

You should initialize a static final variable either in a static initializer, or directly. So either

static final JButton button = new JButton();

static final JButton button;

static {
  button = new JButton();
}

Java语言规范有更多关于它的文档:关于最终变量的部分说明了为什么你得到编译错误:

The Java language specification has some more documentation about it: the section about final variables specifies why you get the compile error:


如果分配了最终变量,那么这是一个编译时错误,除非它是绝对未分配的(§16)在作业之前。

It is a compile-time error if a final variable is assigned to unless it is definitely unassigned (§16) immediately prior to the assignment.

第16章谈到明确的任务

这篇关于Java - 最终变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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