当Java虚拟机初始化一个类时,要求它的所有父类都已经初始化,但是这条规则不适于接口
1) 当初始化一个类时,并不会先初始化它所实现的类的接口。
2) 在初始化一个接口时,并不会先初始化它的父接口
因此,一个父接口并不会因为它的子接口或者实现类的初始化而初始化。只有当程序首次使用特定接口的镜头变量时,才会导致该接口的初始化。
当初始化一个类时,并不会先初始化它所实现的类的接口 Sample
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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 ; } |
打印结果
1 | 6 |
如果接接口改为class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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 这句话。
在初始化一个接口时,并不会先初始化它的父接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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 " ); } }; } |
打印结果
1 2 | MyParent5_1 invoked Thread[Thread- 0 , 5 ,main] |
作者:Work Hard Work Smart
出处:http://www.cnblogs.com/linlf03/
欢迎任何形式的转载,未经作者同意,请保留此段声明!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程
2015-06-08 Eclipse 常用快捷键的使用