您的位置:首页 > 编程语言 > Java开发

Java 代码块

2018-02-03 13:54 232 查看
·普通代码块

public class CodeSection {
public static void main(String[] args) {
{// 普通代码块
String str = "渣渣辉";// 局部变量
System.out.println("姓名:" + str);
}
String str = "骨天咯";// 全局变量
System.out.println("姓名:" + str);
}
}
=============分割线=============

·构造块

class BlueMoon2017 {
public BlueMoon2017() {
System.out.println("嗨~我是渣渣辉");
}

{
System.out.println("嗨!我是骨天咯!");
}

}

public class CodeSection {
public static void main(String[] args) {
new BlueMoon2017();
new BlueMoon2017();
new BlueMoon2017();

}
}


在构造块里优先调用于构造方法。



=============分割线=============

·静态块

class BlueMoon2017 {
public BlueMoon2017() {
System.out.println("嗨~我是渣渣辉");
}

static {
System.out.println("嗨!我是骨天咯!");
}

}

public class CodeSection {
public static void main(String[] args) {
new BlueMoon2017();
new BlueMoon2017();
new BlueMoon2017();

}
}
静态块优先调用于构造方法,且只执行一次。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息