您的位置:首页 > 编程语言 > Java开发

Java中类的初始化顺序

2017-03-08 12:48 197 查看
先写代码分析,以后再补文章内容

父类:

package cn.tom.init;

/**
* Created by lenovo on 2017/3/8.
*/
public class ParentInit {

private static String parentStr = "我是静态字符串parentStr";
private String parentStr2 = "我是字符串parentStr";

public ParentInit() {
System.out.println("我是构造器ParentInit" + "---------" + 7);
}

static {
System.out.println("静态代码块中===" + parentStr + "----------" + 1);
System.out.println("我是静态代码块ParentInit" + "---------" + 2);
}

{
System.out.println(parentStr2 + "-----------" + 5);
System.out.println("我是代码块ParentInit" + "----------" + 6);
}

static void get() {
System.out.println("我是静态方法ParentInit" + "-----------" + 11);
}

void query() {
System.out.println("我是方法ParentInit");
}
}
子类:
package cn.tom.init;

/**
* Created by lenovo on 2017/3/8.
* 类的初始化顺序
*/
public class ChildInit extends ParentInit {

private static String childStr = "我是静态字符串childStr";
private String childStr2 = "我是字符串childStr";

public ChildInit() {
System.out.println("我是构造器ChildInit" + "----------" + 10);
}

static {
System.out.println("静态代码块" + childStr + "---------" + 3);
System.out.println("我是静态代码块ChildInit" + "----------" + 4);
}

{
System.out.println("代码块中" + childStr2 + "----------" + 8);
System.out.println("我是代码块ChildInit" + "-----------" + 9);
}

static void get() {
System.out.println("我是方法ChildInit");
}

@Override
void query() {
System.out.println("我是方法ChildInit" + "--------" + 12);
}

public static void main(String[] args) {
ParentInit parentInit = new ChildInit();
parentInit.get();//此处调用的是父类的,静态方法不能重写
parentInit.query();//此处调用时子类的
}
}
运行效果:



由以上得出结论:

1、父类的【父类静态变量】>【父类静态代码块】>【子类静态变量】>【子类静态代码块】>【父类成员变量】>【父类代码块】>【父类构造器】>【子类成员变量】>【子类代码块】>【子类构造器】

2、子类不能重写父类的静态方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息