JVM 初始化阶段类的继承

创建如下Demo

package com.example.jvm.classloader;


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 MyTest9 {
    static {
        System.out.println("MyTest9  static block");
    }

    public static void main(String[] args) {

        System.out.println(Child.b);
    }
}

  运行结果

MyTest9  static block
Parent static block
Child static block
4

  

创建Demo2

package com.example.jvm.classloader;



class Parent2{
    static  int a  = 3;

    static {
        System.out.println("Parent2 static block");
    }
}

class  Child2 extends  Parent2{

    static  int b  = 4;

    static {
        System.out.println("Child2 static block");
    }

}
public class MyTest10 {
    static {
        System.out.println("MyTest10 static block");  //静态块被打印,说明该类被初始化了。
    }

    public static void main(String[] args) {

        Parent2 parent2;

        System.out.println("______________");

        parent2 = new Parent2();

        System.out.println(parent2.a);

        System.out.println("______________");

        System.out.println(Child2.b);

    }

}

  打印结果:

MyTest10 static block
______________
Parent2 static block
3
______________
Child2 static block
4

  

创建Demo3

class Parent3{
    static  int a  = 3;

    static {
        System.out.println("Parent3 static block");
    }

    static void doSomething(){
        System.out.println("do something");
    }
}

class  Child3 extends  Parent3{

    static  int b  = 4;

    static {
        System.out.println("Child3 static block");
    }

}
public class MyTest11 {

    public static void main(String[] args) {

        //变量定义在哪里,就是对哪个类的主动使用。如a定义在Parent3中,那就是对Parent3的主动使用
        System.out.println(Child3.a);
        System.out.println("-----------");

        //静态方法定义在哪里,就是对哪个类的主动使用。如doSomething定义在Parent3中,那就是对Parent3的主动使用
        Child3.doSomething();

    }

}

  打印结果

Parent3 static block
3
-----------
do something

  

猜你喜欢

转载自www.cnblogs.com/linlf03/p/10994652.html