java加载顺序

本文章主要是自己在网上学习了别人的文章后写的,其中例子也是直接复制别人的。写着个文章是为了加深记忆,以后忘了也可以翻看下。


java类加载主要有静态static变量、静态初始化块、非静态变量、非静态初始化块和构造方法加载顺序。

加载的顺序如下:

1、同一个类中加载优先级:静态static变量>静态初始化块>非静态变量>非静态初始化块>构造方法。

2、父类和子类加载优先级:

父类静态static变量>父类静态初始化块>子类静态static变量>子类静态初始化块>父类非静态变量>父类非静态初始化块>父类构造方法>子类非静态变量>子类非静态初始化块>子类构造方法


如下是相关例子 ,可以验证上述的结果:



package com.bq.tets.load;


public class Parent 
{
   public static int t = parentStaticMethod2();
   int a = parentStaticMethod3();
  //public static int t = 6;
   
   //父类非静态初始化块
   {
       System.out.println("父类非静态初始化块");
   }
   
   //父类静态初始化块
   static
   {
       System.out.println("父类静态初始化块");
   }
   
   //父类的构造方法
   public Parent()
   {
       System.out.println("父类的构造方法");
   }
   
   //父类类的静态方法
   public static int parentStaticMethod()
   {
       System.out.println("父类类的静态方法");
       return 10;
   }
   
   //父类的静态方法2
   public static int parentStaticMethod2()
   {
       System.out.println("父类的静态方法2,为了验证static静态变量");
       return 9;
   }
   
   //父类的静态方法3
   public static int parentStaticMethod3()
   {
       System.out.println("父类的静态方法3,为了验证非静态变量");
       return 9;
   }
 
   //销毁父类
   @Override
   protected void finalize() throws Throwable
   {
       // TODO Auto-generated method stub
       super.finalize();
       System.out.println("销毁父类");
   }
   


}










package com.bq.tets.load;


public class Child extends Parent
{
public static int m = childStaticMethod2();
int n = childStaticMethod3();
//子类非静态初始化块
{
        System.out.println("子类非静态初始化块");
    }

//子类静态初始化块
    static
    {
        System.out.println("子类静态初始化块");
    }
    
    //子类的构造方法
    public Child()
    {
        System.out.println("子类的构造方法");
    }
    
    //子类的静态方法
    public static int childStaticMethod()
    {
        System.out.println("子类的静态方法");
        return 1000;
    }
    
    //子类的静态方法
    public static int childStaticMethod2()
    {
        System.out.println("子类的静态方法,为了验证静态static变量");
        return 1000;
    }
    
    //子类的静态方法
    public static int childStaticMethod3()
    {
        System.out.println("子类的静态方法,为了验证非静态变量");
        return 1000;
    }
    
    
    //销毁子类
    @Override
    protected void finalize() throws Throwable
    {
        // TODO Auto-generated method stub
        super.finalize();
        System.out.println("销毁子类");
    }


}








package com.bq.tets.load;


public class TestLoad 
{
public static void main(String[] arg) throws Throwable
{
//Parent.parentStaticMethod();
//int a = Parent.t;
//Parent parent = new Parent();
Child child = new Child();

child.finalize();
}


}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值