Java 初始化
Posted lzzz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 初始化相关的知识,希望对你有一定的参考价值。
1.初始化顺序
- 即使没有显示地使用static关键字,构造器实际上也是静态方法。因此,当首次创建对象时,或者类的静态方法/静态域首次被访问时,java解释器必须查找类路径,以定位class文件。
- 然后载入class,有关静态初始化的所有动作都会执行。因此,静态初始化只有在Class对象首次加载的时候进行一次。
- 当用new创建对象的时候,首次将在堆上为对象分配足够的储存空间。
- 这块存储空间会被清零,这就自动地将对象中的所有基本类型数据都设置为默认值,而引用则被设置为null。
- 执行所有出现于字段定义处的初始化动作。
- 执行构造器。
- 如有父类将会先初始化父类。
- 无特殊修饰符的变量会按书写顺序初始化。
package cn.lz.base; /** * 初始化 * @author lzzz * */ public class J17100805 { static { System.out.println("father static{}"); } { System.out.println("father {}"); } private int id = print("father private int id"); private static int staticId = print("father private static int"); public static int print(String str) { System.out.println(str); return 1; } public static void main(String[] args) { J17100805 j1; // static代码块会被执行 System.out.println("--------我在j1之后--------"); J17100805 j2 = new J17100805(); System.out.println("--------我在j2之后--------"); J17100805 j3 = new J17100805(); System.out.println("\n--------我是分割线--------\n"); J171008051 jj1; System.out.println("--------我在jj1之后--------"); J171008051 jj2 = new J171008051(); System.out.println("--------我在jj2之后--------"); J171008051 jj3 = new J171008051(); /**
out:
father static{} father private static int --------我在j1之后-------- father {} father private int id --------我在j2之后-------- father {} father private int id --------我是分割线-------- --------我在jj1之后-------- child static{} child private static int father {} father private int id child {} child private int id --------我在jj2之后-------- father {} father private int id child {} child private int id */ } }
package cn.lz.base; /** * 初始化 * @author lzzz * */ public class J17100805 { static { System.out.println("father static{}"); } { System.out.println("father {}"); } private int id = print("father private int id"); private static int staticId = print("father private static int"); public static int print(String str) { System.out.println(str); return 1; } public static void main(String[] args) { // J17100805 j1; // static代码块会被执行 // System.out.println("--------我在j1之后--------"); // J17100805 j2 = new J17100805(); // System.out.println("--------我在j2之后--------"); // J17100805 j3 = new J17100805(); // System.out.println("\n--------我是分割线--------\n"); J171008051 jj1; System.out.println("--------我在jj1之后--------"); J171008051 jj2 = new J171008051(); System.out.println("--------我在jj2之后--------"); J171008051 jj3 = new J171008051(); /**
out:
father static{} father private static int --------我在jj1之后-------- child static{} child private static int father {} father private int id child {} child private int id --------我在jj2之后-------- father {} father private int id child {} child private int id */ } }
以上是关于Java 初始化的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Swift 使用此代码片段为 iOS 应用程序初始化 SDK?