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]
    

      

  • 相关阅读:
    【转载】JAVA中线程的两种实现方法-实现Runnable接口和继承Thread类
    JAVA详设——UML(用例图、类图、时序图)
    FreeTDS-SQL Server在linux和unix下的免费驱动
    【转】移动oracle LOB索引到其他表空间
    [转载]JDBC读写Oracle的CLOB、BLOB
    JProgressBar与Timer的配套使用
    网页美工设计及源码
    分析SignalTap的仿真结果
    用SignalTap进行硬件仿真
    单周期CPU设计的理论基础
  • 原文地址:https://www.cnblogs.com/linlf03/p/10990981.html
Copyright © 2011-2022 走看看