java 继承类加载顺序

                                                        155537_cLhp_2370261.jpg

加载顺序为

父类静态定义初始化
子类静态定义初始化

父类定义初始化
父类构造方法
子类定义初始化
子类构造方法
package xu.jin;
 
class Insect{
    private int i=print("hello i");
    Insect(){System.out.println("Insect"+i);}
    {
        System.out.println("1");
        System.out.println("2");
    }
    static{
        System.out.println("3");
        System.out.println("4");
    }
    static int print(String str){
        System.out.println(str);
        return 2;
    }
    static int x1=print("static Insect");
}
 
 class hello extends Insect{
  private int j=print(" hello j");
  static int x2=print("static hello");
  hello(){
      System.out.println("hello"+j);
      }
    {
        System.out.println("11");
        System.out.println("22");
    }
static{
        System.out.println("33");
        System.out.println("44");
    }
 
    public static void main(String[] args) {
            // TODO Auto-generated method stub
            hello sCat=new hello();
            //Insect ins=new Insect();
     System.out.println("hello world");
    }
}

输出为:

3
4
static Insect
static hello
33
44
hello i
1
2
Insect2
 hello j
11
22
hello2
hello world
首先加载类,再初始化。想想也知道肯定先加载基类,再子类,初始化也是,子类是在基类基础上进行添加,肯定先要初始化基类再子类。 先初始化static的变量,在执行main()方法之前就需要进行加载。再执行main方法,如果new一个对象,则先对这个对象类的基本成员变量进行初始化(非方法),包括构造代码块,这两种是按照编写顺序按序执行的,再调用构造函数。 关于继承的初始化机制,首先执行含有main方法的类,观察到hello类含有基类Insect,即先加载Insect类的static变量,再加载hello类的static变量。加载完static变量之后,调用main()方法,new hello则先初始化基类的基本变量和构造代码块,再调用基类的构造方法。然后再初始化子类hello的基本变量和构造代码块,再执行子类的构造函数。


转载于:https://my.oschina.net/FTDFW/blog/535445

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值