编程语言
首页 > 编程语言> > java – 在内部类中使用非final变量

java – 在内部类中使用非final变量

作者:互联网

我是Java的新手,并且几天以来一直在做一些基本的编码.今天在处理变量和内部类时,我在内部类中使用非final变量时遇到困难.

我正在使用testNG框架进行工作,所以这是我正在尝试的场景,

=========

public class Dummy extends TestNG {
   @Override
   public void setUp() throws Exception {
      log.error("Setup Goes here");
   }

   @Override
   public void test() throws Exception {
        String someString = null;
        try { 
         someString = "This is some string";
      } catch (Exception e) {
         log.error(e.getMessage());
      }
         Thread executeCommand = new Thread(new Runnable() {
            @Override 
            public void run() {       
               try {
                  runComeCommand(someString, false); <=====ERROR LINE
               } catch (Exception e) {
                  log.error(e.getMessage());
               }
            }
         });
   }

   @Override
   public void cleanUp() throws Exception {
   }
}

==========

当我编写上面的代码时,它抛出一个错误,说“不能引用内部类中的非final变量”.所以我实现了eclips提供的一个建议,即在父类中声明someString变量.现在代码看起来像这样,

==========

public class Dummy extends TestNG {
   String someString = null; <=====Moved this variable from test() to here
   @Override
   public void setUp() throws Exception {
        log.error("Setup Goes here");
   }
   @Override
   public void test() throws Exception {
                <same code goes here>
   }

   @Override
   public void cleanUp() throws Exception {
   }
}

==========

现在它在eclips中没有显示任何错误.
我想知道,为什么它现在接受内部类中的变量,即使它不是最终的.不应该失败并出现同样的错误吗?这会有效吗?任何帮助都会很棒.

解决方法:

在您的第一个示例中,someString是test中的局部变量.您不能引用非最终局部变量,因为内部类将无法观察到该值的更改.通过将该变量声明为final,在内部类中保留另一个引用(并且在创建实例时已知该变量的值).

在第二个示例中,someString不是局部变量,而是实例1.内部类可以从容器对象引用该变量.

标签:java,variables,inner-classes
来源: https://codeday.me/bug/20190901/1780855.html