java 编译时的初始化顺序

有的时候,java的初始化会对我的工作照成很大影响,所以简单介绍一下,

首先介绍简单的变量的初始化:在类的内部,变量定义的先后顺序决定了初始化的顺序,即使变量定义散布于方法定义之间,它也会先于构造器和方法初始化。

public class Test{
    public static void main(String[] args){
        Test2 test2 = new Test2();
        test2.f();
    }
}
class Test1{
    public Test1(int i){
        System.out.println("this is Test1"+i);
    }
}
class Test2{

    Test1 test1;
    Test1 test11 = new Test1(1);
    public Test2(){
        System.out.println("this is Test2");
        System.out.println("here is test1 "+test1);
        test1 = new Test1(1111);
        test13 = new Test1(33);
    }
    Test1 test12 = new Test1(2);
    public void f(){
        System.out.println("this is f()");
    }
    Test1 test13 = new Test1(3);
}

输出结果为:

this is Test11
this is Test12
this is Test13
this is Test2
here is test1 null
this is Test11111
this is Test133
this is f()

由此可以看出初始化的顺序为:在类的内部,变量定义的先后顺序决定了初始化的顺序,即使变量定义散布于方法定义之间,它也会先于构造器和方法初始化。

即使在构造器或者定义的时候对变量进行了初始化但是这也没办法阻止系统对它进行的默认的初始化;

如果有静态的变量,那么static的变量会优先进行初始化,然后再对普通变量初始化,static变量只初始化一次,当第一次用到这个类的时候进行初始化

转载于:https://www.cnblogs.com/monkeydai/p/4171627.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值