类初始化,
创建时初始化
,main方法所在的类需要先加载和初始化
运行时会初始化 父类,执行clinit(),
1.静态变量显示和赋值代码
2.静态代码块
顺序从上至下
实例初始化 linit
- super()
1.非静态变量赋值
2.非静态代码块
3.顺序上下执行,而对应构造器的代码最后执行
4.每次创建实例对象,调用对应构造器,执行的就是对应的init方法
5.父类实例化时的this是指的是子类,如果调用方法就是子类重写的方法
- final/静态方法 private 方法 不可被重写 ,多态
- super() 最前
- 属性
- 方法
- 构造器 最后
package classLoadOrder;
public class father {
private int i =test();
private static int j =method();
static{
System.out.println("1-");
}
father(){
System.out.println("2-");
}
{
System.out.println("3-");
}
public int test(){
System.out.println("4-");
return 1;
}
public static int method(){
System.out.println("5-");
return 1;
}
}
父类
package classLoadOrder;
public class son extends father{
private int i =test();
private static int j =method();
static{
System.out.println("6-");
}
son(){
System.out.println("7-");
}
{
System.out.println("8-");
}
public int test(){
System.out.println("9-");
return 1;
}
public static int method(){
System.out.println("10-");
return 1;
}
public static void main(String[] args) {
/**
* main 要先加载和初始化
* 加载 执行静态变量和静态变量
* 结果是 5 1 10 6
*/
}
}
执行类加载器
package classLoadOrder;
public class son extends father{
private int i =test();
private static int j =method();
static{
System.out.println("6-");
}
son(){
System.out.println("7-");
}
{
System.out.println("8-");
}
public int test(){
System.out.println("9-");
return 1;
}
public static int method(){
System.out.println("10-");
return 1;
}
public static void main(String[] args) {
/**
* 实例化执行linit
* 1.调用super() 进入 father类, 执行 2. 3 步
* ,方法默认加上this ,this指当前执行的类就是son,重写了father的test()
* 执行输出 9 3 2 9 8 7 两次
* 2.非静态变量,方法 执行
* 3. 构造去
*/
son son = new son();
son son1 = new son();
}
}
1