简体   繁体   English

无法为java中的“final”变量赋值

[英]cannot assign value to “final” variable in java

 private void pushButtonActionPerformed(java.awt.event.ActionEvent evt)
{
    final int c=0;
    final JDialog d=new JDialog();
    JLabel l=new JLabel("Enter the Element :");
    JButton but1=new JButton("OK");
    JButton but2=new JButton("Cancel");
    final JTextField f=new JTextField(10);
    JPanel panel = new JPanel();
    but1.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            c=Integer.parseInt(f.getText());
            d.setVisible(false);
            d.dispose( );
        }
     });
but2.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        d.setVisible(false);
        d.dispose( );
    }
});
}

I am using netbeans 7.1.1. 我正在使用netbeans 7.1.1。 This is my code here i have declared 'c' as "final int" but the line "c=Integer.parseInt(f.getText());" 这是我的代码,我已将'c'声明为“final int”,但行“c = Integer.parseInt(f.getText());” i am getting an error "cannot assign a value to a final variable". 我收到错误“无法为最终变量赋值”。 If i am deleting the word final from the declaration and making it just as "int c" then in the same line i get an error "local variable c cannot be accessed from within a class;needs to be declared final". 如果我从声明中删除单词final并将其作为“int c”,那么在同一行中我得到一个错误“无法从类中访问局部变量c;需要声明为final”。 can anyone tell me why is this happening ? 谁能告诉我为什么会这样?

You've got c declared in a function, and then you've created an anonymous inner class within that function. 你已经在一个函数中声明了c ,然后你在该函数中创建了一个匿名内部类。 This inner class, the ActionListener, persists past the time your function terminates - so it can't assign values to c, because c is local to the function. 这个内部类ActionListener会在函数终止时间之后持续存在 - 因此它无法为c赋值,因为c是函数的本地值。

The warning about "final" is misleading - that's just the compiler telling you that you can't access transient local variables from an anonymous class. 关于“最终”的警告是误导性的 - 只是编译器告诉你不能从匿名类访问瞬态局部变量。 You can't solve the problem just by making c final, as that would prevent any assignment to it at all, but you can make c an instance member of the class pushButtonActionPerformed is in, instead. 你不能仅仅通过使c final来解决问题,因为这会阻止对它的任何赋值,但你可以使c成为类pushButtonActionPerformed的实例成员 Something like this: 像这样的东西:

class Something
{
    int c;

    private void pushButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
        JButton but1=new JButton("OK");
        but1.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                c=Integer.parseInt(f.getText());
            }
        });
    }
}

I'll skip the reasons and cut to the solution: use 我将跳过原因并切入解决方案:使用

final int[] c = {0};
...
c[0] = Integer.parseInt(f.getText());

For the full story refer to this post 有关完整的故事,请参阅这篇文章

but the line "c=Integer.parseInt(f.getText());" 但是行“c = Integer.parseInt(f.getText());” i am getting an error "cannot assign a value to a final variable 我收到错误“无法为最终变量赋值

Right. 对。 The whole point of final variables is that you can only assign to them once, but you're trying to assign to it twice (once in the initialization setting it to 0 , once in your quoted line). final变量的全部内容是你只能分配给它们一次,但是你要尝试两次分配它(一次在初始化设置中它为0 ,一次在你的引用行中)。 From the specification : 规格

A variable can be declared final . 变量可以声明为final A final variable may only be assigned to once. final变量只能分配一次。 Declaring a variable final can serve as useful documentation that its value will not change and can help avoid programming errors. 声明变量final可以作为有用的文档,它的值不会改变,可以帮助避免编程错误。

It is a compile-time error if a final variable is assigned to unless it is definitely unassigned (§16) immediately prior to the assignment. 如果分配了final变量,则为编译时错误,除非在分配之前它是明确未分配的(第16段)。

A blank final is a final variable whose declaration lacks an initializer. 空白final是一个final变量,其声明缺少初始化程序。

Once a final variable has been assigned, it always contains the same value. 一旦分配了final变量,它总是包含相同的值。 If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object. 如果final变量包含对对象的引用,则可以通过对对象的操作来更改对象的状态,但该变量将始终引用同一对象。

(Their emphasis, not mine.) (他们的重点,不是我的。)

Instead of trying to track the state you're storing in c in a variable in the method, track it in a data member in the instance of your anonymous ActionListener you're creating. 而不是尝试跟踪您在方法中的变量中存储c的状态,而是在您正在创建的匿名ActionListener实例的数据成员中跟踪它。

This is the reason that keyword final exists in java. 这就是java中存在关键字final的原因。 The variable is final, ie its value cannot be changed. 变量是最终的,即它的值不能改变。 If you have to change the value do not mark variable as final. 如果必须更改值,请不要将变量标记为final。

a variable is declared with final keyword means its value cannot be changed. 使用final关键字声明变量意味着其值不能更改。 final variable are like constants 最终变量就像常量

final makes the "variable" a constant--you can't change it. final使“变量”成为常数 - 你无法改变它。 As to why the compiler is giving you warnings after you delete the final keyword, we'd need to see the whole code... 至于为什么编译器在你删除final关键字后给你警告,我们需要看到整个代码......

EDIT: 编辑:

 but1.addActionListener(new ActionListener()
 {
     public void actionPerformed(ActionEvent e)
     {
         c=Integer.parseInt(f.getText());
         d.setVisible(false);
         d.dispose( );
     }
  });

I believe this is the segment of code that causes the compiler to fire the warning. 我相信这是导致编译器触发警告的代码段。 You can't use c in this class... 你不能在这堂课中使用c ......

Just remove the final keyword from the declaration and continue your program. 只需从声明中删除final关键字并继续执行您的程序。 As final keyword means the value is unaltered. 作为final关键字意味着价值不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM