• 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变量只初始化一次,当第一次用到这个类的时候进行初始化

  • 相关阅读:
    django_开发报错
    SpringBoot 前后端数据参数交互
    消息队列学习笔记(一)
    2021年调用工商二维码退款查询接口
    2021年调用工商二维码退款接口
    2021年调用工商二维码生成接口及回调接口demo
    调用工商生成二维码接口文档的坑
    使用hutool工具类转换时间
    微信模板消息推送
    pom文件 spring-boot-maven-plugin 爆红
  • 原文地址:https://www.cnblogs.com/monkeydai/p/4171627.html
Copyright © 2020-2023  润新知