JAVA - 深入JAVA 虛擬機器 3

來源:互聯網
上載者:User

標籤:ati   gets   分享   cat   image   png   for   class   name   

類的初始化時機

package practise;class Parent{        static int a =3;    static{                System.out.println("Parent static block");    }}class Child extends Parent{    static int b = 4;    static{                System.out.println("Child static block");    }}public class Test4 {        static{                System.out.println("Test4 static block");    }    public static void main(String[] args) {                System.out.println(Child.b);            }}

Result:
Test4 static block
Parent static block
Child static block
4
package practise;class Parent5{        static int a =3;    static{                System.out.println("Parent5 static block");    }}class Child5 extends Parent5{    static int b = 4;    static{                System.out.println("Child5 static block");    }}public class Test5 {        static{                System.out.println("Test5 static block");    }    public static void main(String[] args) {                Parent5 parent = new Parent5();                System.out.println(Parent5.a);        System.out.println(Child5.b);            }}

Result:
Test5 static block
Parent5 static block
3
Child5 static block
4

程式中對子類的“主動使用”會導致父類被初始化;但對父類的“主動”使用並不會導致子類
初始化。

調用 ClassLoader類的loadClass方法載入一個類,並不是對類的主動使用,不會導致類的初始化。

package practise;class C{        static{                System.out.println("Class C");    }}public class Test6 {    public static void main(String[] args) {                ClassLoader loader = ClassLoader.getSystemClassLoader();                try {            Class<?> clz = loader.loadClass("practise.C");            System.out.println("----------------");            clz = Class.forName("practise.C");                    } catch (ClassNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}

Result:
----------------
Class C

 

JAVA - 深入JAVA 虛擬機器 3

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.