Java 类与接口的初始化、实例创建及终结机制解析
在 Java 编程中,类与接口的初始化、新类实例的创建以及类实例的终结是非常重要的概念。理解这些机制有助于我们编写出更高效、更稳定的 Java 代码。下面将详细介绍这些机制的相关内容。
1. 类与接口初始化示例分析
先来看一个测试程序:
interface I {
int i = 1, ii = Test.out("ii", 2);
}
interface J extends I {
int j = Test.out("j", 3), jj = Test.out("jj", 4);
}
interface K extends J {
int k = Test.out("k", 5);
}
class Test {
public static void main(String[] args) {
System.out.println(J.i);
System.out.println(K.j);
}
static int out(String s, int i) {
System.out.println(s + "=" + i);
return i;
}
}
该程序的输出结果为:
1
j=3
jj=4
3
对 J.i 的引用是对一个编译时常量字段的引用,因此不会导致接口 I 被初始化。而对
超级会员免费看
订阅专栏 解锁全文

1124

被折叠的 条评论
为什么被折叠?



