静态代码块 + 找不到符号

huangapple go评论137阅读模式
英文:

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>



huangapple
  • 本文由 发表于 2020年4月8日 23:10:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/61103972.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定