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

  • 相关阅读:
    [leetcode-135-Candy]
    [leetcode-151-Reverse Words in a String]
    [leetcode-139-Word Break]
    [leetcode-129-Sum Root to Leaf Numbers]
    [leetcode-143-Reorder List]
    [leetcode-141-Linked List Cycle]
    oracle 环境变量(中文显示乱码)
    Oracle 自增长id
    Spring.net 事件的注入
    Spirng.net 替换任意方法
  • 原文地址:https://www.cnblogs.com/monkeydai/p/4171627.html
Copyright © 2011-2022 走看看