代码块
代码块分类:
1.普通代码块
2.构造代码块
3.静态代码块
4.同步代码块
代码块不能独立运行,须要依赖于其他配置,格式是:{ //代码块 }。
1.普通代码块
普通代码块,在方法名后(或方法体内)用一对"{}"括起来的数据块,并通过方法调用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
package cn.com.daimakuai; /** * PuTongDaiMaiKuai *@author:hushaoyu *2017-2-13上午9:27:02 *@描述:普通代码块 */ public class PuTongDaiMaiKuai { public static void main(String[] args) { /**"{}"括起来的普通代码块;这里的变量x=100作用范围从"{"开始"}"结束,所以与下面的变量x=200互不影响, * 如果将下面的变量放在普通代码前面将编译错误,因为main的代码块范围比较大 */ { int x = 100 ; System.out.println( "普通代码块:" +x); } int x = 200 ; System.out.println( "main方法:" +x); } /** * 结果输出: 普通代码块:100 main方法:200 */ } |
2.构造代码块
构造代码块:在类中直接定义的,没有任何前缀、后缀以及修饰符的代码块。
构造代码块和构造方法一样都是在对象生成时被调用,但调用时机比构造方法早,所以构造代码块可以用来初始化成员变量。如果一个类中有多个构造方法,这些构造方法都需要初始化成员变量,那么可以把每个构造方法中相同的代码部分抽取出来,集中一起放在构造代码块中,利用构造代码块来初始化共有的成员变量,减少重复代码。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
package cn.com.daimakuai; /** * ConstroctDaimakuai * @author:hushaoyu * @2017-2-13上午10:02:55 * @描述:构造代码块 */ public class ConstroctDaimakuai { public static void main(String[] args) { Person p1 = new Person(); System.out.println( "*******************" ); Person p2 = new Person( "hushaoyu" ); } } // Person类 class Person { private int x; private String name; // 构造代码块 { System.out.println( "构造代码块执行-------" ); // 对类的成员变量x进行初始化,如果不放置在代码块中,要达到同样效果,需要分别出现在2个构造方法中。 x = 100 ; } // 无参构造方法 Person() { System.out.println( "构造方法执行-------" ); name = "huyuyu" ; show(); } // 有参构造方法 Person(String name) { System.out.println( "构造方法执行-------" ); this .name = name; show(); } /** * show方法 */ private void show() { System.out.println( "welcome!" + name); System.out.println( "x=" + x); } /**结果输出: 构造代码块执行------- 构造方法执行------- welcome!huyuyu x=100 ******************* 构造代码块执行------- 构造方法执行------- welcome!hushaoyu x=100 */ } |
3.静态代码块
静态代码块:static修饰并用"{}括起来的代码块。
特点:用来初始化静态成员变量,最先执行(随着类的加载而加载),只执行一次。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
package cn.com.daimakuai; /** * Staticdaimakuai *@author:hushaoyu *2017-2-13上午10:45:49 *@描述:静态代码块 */ public class Static daimakuai { public static void main(String[] args) { System.out.println( "main方法执行-------" ); System.out.println( "***创建第1个对象***" ); new Staticdaimakuai(); System.out.println( "***创建第2个对象***" ); new Staticdaimakuai(); System.out.println( "***创建第3个对象***" ); new Staticdaimakuai(); } //静态代码块 static { System.out.println( "静态代码块执行-------" ); } //构造方法 Staticdaimakuai(){ System.out.println( "构造方法执行------" ); } //构造代码块 { System.out.println( "构造代码块执行------" ); } /** 结果输出: 静态代码块执行------- main方法执行------- ***创建第1个对象*** 构造代码块执行------ 构造方法执行------ ***创建第2个对象*** 构造代码块执行------ 构造方法执行------ ***创建第3个对象*** 构造代码块执行------ 构造方法执行------ */ } |