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]
    

      

  • 相关阅读:
    关系型数据库和非关系型数据库的区别
    总结篇3-python数据结构和算法
    总结篇2-python进阶
    总结篇1-python基础
    测试sql星级判定函数
    1、Anyproxy简介
    Python内置logging模块-- 日志
    python+ selenium 绕过浏览器检测
    python-selenium,解决 遇到阿里无痕登录验证
    seldom
  • 原文地址:https://www.cnblogs.com/linlf03/p/10990981.html
Copyright © 2011-2022 走看看