java字段顺序_Java中数据字段的初始化顺序

一般来说:

1)静态字段成员(通常是静态初始化程序)

2)非静态领域成员

3)构造函数

但是,您可以使用如下代码片段对其进行测试:

public class TestClass {

int i = 10;

static int j = 20;

public TestClass() {

// TODO Auto-generated constructor stub

System.out.println(i);

i = 20;

System.out.println(i);

}

public static void main(String[] args) {

new TestClass();

}

}

引用伟大的“ Java思维”:

Within a class, the order of initialization is determined by the order that the variables are

defined within the class. The variable definitions may be scattered throughout and in between method definitions, but the variables are initialized before any methods can be

called—even the constructor.

……………………………..

There’s only a single piece of storage for a static, regardless of how many objects are created.

You can’t apply the statickeyword to local variables, so it only applies to fields. If a field is a

staticprimitive and you don’t initialize it, it gets the standard initial value for its type. If it’s

a reference to an object, the default initialization value is null.

要总结创建对象的过程,请考虑一个称为Dog的类:

>即使未明确使用static关键字,构造函数实际上还是

静态方法.因此,第一次创建Dog类型的对象,或者第一次创建

访问Dog类的静态方法或静态字段时,Java解释器必须

找到Dog.class,它通过搜索类路径来完成.

>在加载Dog.class时(创建一个Class对象,您将在后面了解),所有

它的静态初始化程序将运行.因此,静态初始化仅发生一次,因为

第一次加载类对象.

>创建新的Dog()时,首先要构建Dog对象

为堆上的Dog对象分配足够的存储空间.

>将该存储空间擦除为零,自动设置该Dog中的所有原语

反对他们的默认值(数字为零,布尔值和

char)和对null的引用.

>将执行在字段定义时发生的所有初始化.

>构造函数被执行,这实际上可能涉及大量活动,尤其是在涉及继承时.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值