java 对象初始化属性_Java类属性和对象属性的初始化顺序

一个例子: public class Test {

static String a = "string-a";

static String b;

String c = "stirng-c";

String d;

static {

printStatic("before static");

b = "string-b";

printStatic("after static");

}

public static void printStatic(String title) {

System.out.println("---------" + title + "---------");

System.out.println("a = \"" + a + "\"");

System.out.println("b = \"" + b + "\"");

}

public Test() {

print("before constructor");

d = "string-d";

print("after constructor");

}

public void print(String title) {

System.out.println("---------" + title + "---------");

System.out.println("a = \"" + a + "\"");

System.out.println("b = \"" + b + "\"");

System.out.println("c = \"" + c + "\"");

System.out.println("d = \"" + d + "\"");

}

public static void main(String[] args) {

new Test();

}

}

运行结果:

-----------before static-----------

a = "string-a"

b = "null"

-----------after static-----------

a = "string-a"

b = "static-b"

-----------before constructor-----------

a = "string-a"

b = "static-b"

c = "string-c"

d = "null"

-----------after constructor-----------

a = "string-a"

b = "static-b"

c = "string-c"

d = "string-d"

结果分析:

由这个例子可以看出Java类属性和对象属性的初始化顺序如下

1 类属性(静态变量)定义时的初始化,如范例中的 static String a = "string-a"

2 static块中的初始化代码,如范例中的 static{} 中的 b = "string-b"

3 对象属性(非静态变量)定义时的初始化,如范例中的 String c = "string-c"

4 构造方法(函数)中的初始化代码,如范例构造方法中的 d = "string-d"

代码出处:《Java从入门到精通》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值