我正在使用 JDK9 的 jshell。
我刚刚创建了一个最终变量并为其分配了一个值。
在下一行中,我只是修改了值。令我惊讶的是,修改最终变量时没有错误。
以下是代码片段:
jshell> final int r = 0;
| Warning:
| Modifier 'final' not permitted in top-level declarations, ignored
| final int r = 0;
| ^---^
r ==> 0
jshell> r = 1;
r ==> 1
jshell> System.out.println("r = "+r)
r = 1
它是 jshell 所期望的吗?或者还有其他方法可以在 jshell 中处理最终变量?
最佳答案
虽然不应该在顶层创建最终变量。但我想没有严格的方法来限制这种用法。
来自 JShell.eval
周围的文档
The modifiers
public
,protected
,private
,static
, andfinal
are not allowed on op-level declarations and are ignored with a warning.Synchronized, native, abstract, and default top-level methods are not allowed and are errors.
If a previous definition of a declaration is overwritten then there will be an event showing its status changed to OVERWRITTEN, this will not occur for dropped, rejected, or already overwritten declarations.
当您执行
jshell
时,上述警告非常明显。详细模式如下:关于最终变量在 jshell 中无法正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47880733/