zoukankan      html  css  js  c++  java
  • 初始化对于类和接口的异同点深入解析

    当Java虚拟机初始化一个类时,要求它的所有父类都已经初始化,但是这条规则不适于接口

    1) 当初始化一个类时,并不会先初始化它所实现的类的接口。

    2) 在初始化一个接口时,并不会先初始化它的父接口

    因此,一个父接口并不会因为它的子接口或者实现类的初始化而初始化。只有当程序首次使用特定接口的镜头变量时,才会导致该接口的初始化。

    当初始化一个类时,并不会先初始化它所实现的类的接口 Sample

    public class MyTest5 {
    
        public static void main(String[] args) {
            System.out.println(MyChild5.b);
           
        }
    }
    
    interface MyParent5{
    
    
        public static Thread thread = new Thread(){
            {
                //实例化代码块
                System.out.println("MyParent 5 invoked ");
            }
        };
    
    }
    
    class MyChild5 implements MyParent5{
        public static  int b = 6;
    
    }
    

      打印结果

    6
    

      

    如果接接口改为class

    public class MyTest5 {
    
        public static void main(String[] args) {
            System.out.println(MyChild5.b);
    
        }
    }
    
    class MyParent5{
    
      
        public static Thread thread = new Thread(){
            {
                //实例化代码块
                System.out.println("MyParent 5 invoked ");
            }
        };
    
    }
    
    class MyChild5 extends MyParent5{
        public static  int b = 6;
    
    }
    

      那么就会打印出

    MyParent 5 invoked 这句话。

     在初始化一个接口时,并不会先初始化它的父接口

    public class MyTest5 {
    
        public static void main(String[] args) {
      
            System.out.println(MyParent5_1.thread);
        }
    }
    
    
    
    interface MyGrandpa5_1 {
        public static Thread thread = new Thread(){
            {
                //实例化代码块
                System.out.println("MyGrandpa5_1 invoked ");
            }
        };
    }
    
    interface MyParent5_1 {
        public static  Thread thread = new Thread(){
            {
                //实例化代码块
                System.out.println("MyParent5_1 invoked ");
            }
        };
    }
    

      打印结果

    MyParent5_1 invoked 
    Thread[Thread-0,5,main]
    

      

  • 相关阅读:
    Codeforces Round #502 (in memory of Leopoldo Taravilse, Div. 1 + Div. 2) E. The Supersonic Rocket
    Codeforces Round #500 (Div. 2) D
    AtCoder Grand Contest 026 D
    Codeforces Round #495 (Div. 2) Sonya and Matrix
    AtCoder Regular Contest 100 E
    1013 数素数
    1010 一元多项式求导(用while接收输入)
    1009 说反话(字符串、栈)
    L2-006 树的遍历 (后序中序求层序)
    L2-004 这是二叉搜索树吗?
  • 原文地址:https://www.cnblogs.com/linlf03/p/10990981.html
Copyright © 2011-2022 走看看