我正在读一本书,有一些例子只有花括号的程序
例如
public static void main(String args[]){
//what is the uses of curly braces here.
{
//some code
}
}
Run Code Online (Sandbox Code Playgroud)
Gor*_*vic 25
这是一个代码块.在那里声明的变量在上部块(这些curlies之外的方法体)中是不可见的,即它们具有更有限的范围.
Cod*_*nci 12
要小心,它并不像其他人所建议的那样始终是初始化块.在您的情况下,它是一个称为代码块或块的变量范围机制.
如果它在方法之外,那就是!
例
public class MyClass {
{
// this is an initialisation block
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果它在方法内部,则不是!在这种情况下(在您的示例中就是这种情况),它是一个代码块.在花括号内初始化的任何东西在外面都看不到
例
public static void main(String args[]){
{
String myString = "you can't see me!";
}
System.out.println(myString); // this will not compile because myString is not visible.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5723 次 |
| 最近记录: |