java静态块+找不到符号
Java14
public class Ex14 {
static String strDef = "At the point of definition";
static {String strBlock = "In a static block";}
public static void main (String [] args){
System.out.println(Ex14.strDef);
System.out.println(Ex14.strBlock);
}
}
结果
$javac Ex14。爪哇
Ex14.java:10: error: cannot find symbol
System.out.println(Ex14.strBlock);
^
symbol: variable strBlock
location: class Ex14
1 error
你能帮我理解为什么会发生这种错误吗
# 1 楼答案
您的
strBlock
变量是静态初始值设定项块中的局部变量。它的范围仅限于该块,就像任何其他局部变量一样。如果希望能够在main
方法中访问它,则需要将其声明为字段: