第一步:加载该类,一个java对象在初始化前会举行类加载,在JVM中生成Class对象。加载一个类会举行以下操纵,下面给出递归形貌。
假如该类有父类,则先加载其父类。
i 初始化该类静态成员
ii 实行该类静态代码块
第二步:建立对象,假如该类有父类,则建立对象时会先建立其父类的对象,外层包裹子类的属性和要领,然后返回子类的援用,下面给出递归形貌。
假如该类有父类,先建立父类的对象。
i 初始化该类一般成员
ii 实行一般代码块
iii 挪用该类组织要领
示例:
该类对象作为成员变量
public class Info{ public Info(String s) { System.out.println(s); } }
父类
public class Parent { public static Info info = new Info("Parent static member"); //静态成员 public Info info2 = new Info("Parent common member"); //一般成员 static { //静态代码块 System.out.println("parent static block"); } { //一般代码块 System.out.println("parent common block"); } public Parent() { //父类组织要领 System.out.println("Parent.Parent()"); } }
子类
public class Child extends Parent{ public static Info info = new Info("Child static member"); //静态成员 public Info info2 = new Info("Child common member"); //一般成员 static { //静态代码块 System.out.println("Child static block"); } { //一般代码块 System.out.println("Child common block"); } public Child() { //子类组织要领 System.out.println("Child.Child()"); } }
下面测试类的加载历程,我们不建立对象,而是直接加载类,并且是加载子类
public class InitObjectTest{ public static void main(String[] args) { try{ //Class.forName("Parent"); Class.forName("Child"); }catch(Exception e){ } //System.out.println("=============== now , we create an Object below ==========="); //new Parent(); } }
测试效果:
测试效果相符上面所写的加载类的划定规矩,先初始化父类静态成员,再实行父类静态块,然后初始化子类静态成员,末了实行子类静态块。我们能够看到静态成员确着实类加载时初始化。
注重:类的加载只举行一次,以后建立对象将不再举行类加载,这也是为何静态代码块只实行一次的缘由。
引荐教程:java入门教程
以上就是java中的对象怎样初始化的细致内容,更多请关注ki4网别的相干文章!