类的加载顺序以及静态成员初始化顺序

Java程序运行时,会首先运行到某类的main()方法,随即开始加载该类,同时对static成员初始化。若该类具有超类,则从根基类开始加载类并初始化类的static成员,因为有时候子类的成员初始化会依赖于基类的初始化成员。错误的理解是:Java运行到程序中,若遇到对类的操作(比如生成类对象)时才加载对应于操作的类并初始化其static成员。

//StaticInitialSequence.java
//The class including main method is loaded while the application goes to the main().

package com.msn.spaces.bryantd001;

class SuperClass{
    private static StringBuffer strBufSuper;
    static{
        strBufSuper=new StringBuffer("strBufSuper is a StringBuffer in the super class.");
        System.out.println(strBufSuper);
    }
}

public class StaticInitialSequence extends SuperClass{
    private static String strSub=new String("strSub is a String in the sub class.");
    static{
        System.out.println(strSub);
    }
    public static void main(String[] args){
        AnotherClass acObj=new AnotherClass();
        StaticInitialSequence sisObj=new StaticInitialSequence();
       
        System.out.println();
        System.out.println("The result I expected in the past are:");
        System.out.println("i=100 is a Integer in another class.");
        System.out.println("strBufSuper is a StringBuffer in the super class.");
        System.out.println("strSub is a String in the sub class.");
    }
}

class AnotherClass{
    private static int i;
    static{
        i=100;
        System.out.println("i= "+i+" is a Integer in another class.");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值