gpt4 book ai didi

Java: 有什么区别?

转载 作者:IT老高 更新时间:2023-10-28 11:40:18 25 4
gpt4 key购买 nike

我无法理解下面的文字... 是否意味着 <clinit>是为空的构造函数?为什么拥有两个不同的版本很重要?

https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html

2.9. Special Methods

At the level of the Java virtual machine, every constructor (§2.12) appears as an instance initialization method that has the special name <init>. This name is supplied by a compiler. Because the name <init> is not a valid identifier, it cannot be used directly in a program written in the Java programming language. Instance initialization methods may be invoked only within the Java virtual machine by the invokespecial instruction, and they may be invoked only on uninitialized class instances. An instance initialization method takes on the access permissions (§2.7.4) of the constructor from which it was derived.

A class or interface has at most one class or interface initialization method and is initialized (§2.17.4) by invoking that method. The initialization method of a class or interface is static and takes no arguments. It has the special name <clinit>. This name is supplied by a compiler. Because the name <clinit> is not a valid identifier, it cannot be used directly in a program written in the Java programming language. Class and interface initialization methods are invoked implicitly by the Java virtual machine; they are never invoked directly from any Java virtual machine inw2struction, but are invoked only indirectly as part of the class initialization process.

最佳答案

<init>是实例的(或其中一个)构造函数,并且是非静态字段初始化。

<clinit>是类的静态初始化 block ,以及静态字段初始化。

class X {

static Log log = LogFactory.getLog(); // <clinit>

private int x = 1; // <init>

X(){
// <init>
}

static {
// <clinit>
}

}

关于Java:<init> 和 <clinit> 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8517121/

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