gpt4 book ai didi

java - Java 的初始化 - 类 v/s 接口(interface)

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:24:00 25 4
gpt4 key购买 nike

我被困在下面的 java 类和接口(interface)的初始化概念中:

我在下面提到的书中读到以下句子:

An interface is initialized only because a non-constant field declared by the interface is used, never because a subinterface or class that implements the interface needs to be initialized.
But that isn't the case when we initialise any java class.

Thus, initialization of a class requires prior initialization of all its superclasses, but not its superinterfaces.
Initialization of an interface does not require initialization of its superinterfaces.

我的问题是为什么会这样?

任何帮助将不胜感激!

谢谢

PS:书籍 - Bill Venners 的“Inside the Java Virtual Machine”(第 7 章 - 类的生命周期)

最佳答案

您唯一可以在接口(interface)中声明的是方法签名和常量字段。后者可以使用常量值(即字符串文字、整数等,可能以某种组合形式)或使用非常量值(即方法调用)进行初始化。因此,如果接口(interface)没有任何非常量字段,则不需要初始化——一切都在编译时已知。如果程序使用了非常量字段,则必须运行初始化代码以确保为这些字段分配了值。

希望对您有所帮助。

P.S.:那一章网上有here如果有人想完整阅读它。

关于java - Java 的初始化 - 类 v/s 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4843950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com