zoukankan      html  css  js  c++  java
  • 04.接口初始化规则与类加载器准备阶段和初始化阶段的意义

    接口初始化规则

    当一个接口在初始化时,并不要求其父接口都完成了初始化

    只有在真正使用父接口的时候 (如引用接口中所定义的常量时),才会初始化

    public class MyTest5 {
        public static void main(String[] args) {
            System.out.println(MyChild5.b);
        }
    }
    
    interface MyParent5 {
        public static int a = 5;
    }
    
    interface MyChild5 extends MyParent5 {
        public static int b = 6;
    }
    

    类加载器准备阶段

    准备阶段会给

    1. counter1 赋初值 0
    2. singleton 赋初值 null
    3. counter2 赋初值 0

    构造方法不会执行

    public class MyTest6 {
    
        public static void main(String[] args) {
            Singleton singleton = Singleton.getInstance();
    
            System.out.println("counter1: " + Singleton.counter1);
            System.out.println("counter2: " + Singleton.counter2);
        }
    }
    
    class Singleton {
        public static int counter1 = 1;
    
        private static Singleton singleton = new Singleton();
    
        private Singleton() {
            counter1++;
            counter2++;
            System.out.println(counter1);
            System.out.println(counter2);
        }
    
        public static int counter2 = 0;
    
        public static Singleton getInstance() {
            return singleton;
        }
    }
    

    输出为

    2
    1
    counter1: 2
    counter2: 0
    

    类加载器初始化阶段

    初始化阶段开始进行真正赋值

    1. counter1 显式的赋值为 1
    2. singleton 的值会导致构造方法的执行,导致 counter1++ 变为 2,counter2++ 变为 1
    3. counter2 = 0,会导致 counter2 的值变为 0

    没有修不好的电脑
  • 相关阅读:
    DS博客作业03--树
    DS博客作业02--栈和队列tt
    DS博客作业02--线性表
    c博客06-结构体&文件
    C博客作业05--指针
    C语言博客作业04--数组
    C语言博客作业03--函数
    图书馆
    DS博客作业05——查找
    DS博客作业04——图
  • 原文地址:https://www.cnblogs.com/duniqb/p/12702450.html
Copyright © 2011-2022 走看看