英文:
Static block + cannot find symbol
问题
**Java 14**
public class Ex14 {
static String strDef = "在定义的位置";
static {String strBlock = "在静态块中";}
public static void main (String [] args){
System.out.println(Ex14.strDef);
System.out.println(Ex14.strBlock);
}
}
**Result**
$ javac Ex14.java
Ex14.java:10: 错误: 找不到符号
System.out.println(Ex14.strBlock);
^
符号: 变量 strBlock
位置: 类 Ex14
1 错误
**你能帮我理解一下为什么会出现这个错误吗?**
英文:
Java 14
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);
}
}
Result
$ javac Ex14.java
Ex14.java:10: error: cannot find symbol
System.out.println(Ex14.strBlock);
^
symbol: variable strBlock
location: class Ex14
1 error
Could you help me understand why this error happens?
答案1
得分: 0
你的 strBlock
变量是静态初始化块内的局部变量。它的作用域限定在该块内,就像任何其他局部变量一样。如果你想在 main
方法中能够访问它,你需要将其声明为一个字段:
static strBlock; // 静态字段声明
static {
// 静态字段初始化
strBlock = "在静态块中初始化";
}
英文:
Your strBlock
variable is a local variables within the static initializer block. Its scope is limited to that block, just like any other local variable. If you want to be able to access it in the main
method, you'll need to declare it as a field:
static strBlock; // Static field declaration
static {
// Static field initialization
strBlock = "Initialized in a static block";
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论