JVM initialization phase class inheritance

Create the following 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);
    }
}

  operation result

MyTest9  static block
Parent static block
Child static block
4

  

 

Creating 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);

    }

}

  Print Results:

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

  

 

Creating Demo3

Parent3 {class 
    static int = A. 3; 

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

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

class {Child3 the extends Parent3 

    int. 4 B = static; 

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

} 
public class MyTest11 { 

    public static void main (String [] args) { 

        // where the variables are defined, to which class is actively used. As defined in a Parent3 in that the active use of Parent3 
        System.out.println (Child3.a); 
        System.out.println ( "-----------");

        // define where the static methods, which class is for active use. As defined in Parent3 the doSomething, that is used for active Parent3 
        Child3.doSomething (); 

    } 

}

  Print results

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

  

Guess you like

Origin www.cnblogs.com/linlf03/p/10994652.html