<span style="font-size:18px;">/**
* 作者:crazyandcoder
* 联系:
* QQ : 275137657
* email: lijiwork@sina.com
* 转载请注明出处!
*/ </span>
java代码块
一、构造代码块
1、执行顺序
每次new 对象时执行,优先于构造函数的执行。
2、代码:
1 class test {
2
3 //构造函数
4 public test() {
5 System.out.println("构造函数代码块");
6 }
7
8 //有参数构造函数
9 public test(String str) {
10 System.out.println("构造函数代码块" + str);
11 }
12
13 //构造代码块
14 {
15 System.out.println("构造代码块");
16 }
17
18 }
19
20 public class hello {
21
22 public static void main(String[] args) {
23 System.out.println("主代码块");
24 test h = new test();
25 test hh = new test("又创建一个对象");
26 }
27 }
3、执行结果:
二、静态代码块
1、执行顺序
优先于构造代码块,构造函数执行
2、作用
给静态成员初始化
3、代码
public class hello {
public static void main(String[] args) {
System.out.println("主代码块");
test h = new test();
test hh = new test("又创建一个对象");
}
}
class test {
private static int num;
//构造函数
public test() {
System.out.println("构造函数代码块");
}
//有参数构造函数
public test(String str) {
System.out.println("构造函数代码块" + str);
}
//构造代码块
{
System.out.println("构造代码块");
}
//静态代码块
static {
num = 1;
System.out.println("静态代码块");
System.out.println("num=" + num);
}
}
4、结果