什么是 Java 中的 <init> 方法?它可以被覆盖吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20407026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is an <init> method in Java? Can it be overridden?
提问by Sergey Fedorov
<init>
method can be found in stacktrace, for example.
As I understood it represents initialization done in constructor.
<init>
例如,可以在堆栈跟踪中找到方法。据我了解,它代表在构造函数中完成的初始化。
If you try to execute
如果您尝试执行
Object.class.getDeclaredMethod("<init>");
You'll get java.lang.NoSuchMethodException
.
你会得到java.lang.NoSuchMethodException
。
What is this method? When was it added to class? (in compilation - execution terms) Is it virtual, can one anyhowoverride it?
这是什么方法?它是什么时候添加到课堂上的?(在编译 - 执行方面)它是虚拟的,无论如何可以覆盖它吗?
采纳答案by Kai Sternad
Have a look at the Java Virtual Machine Specification, chapter 2.9. It say on the <init>
name:
查看Java 虚拟机规范,第 2.9 章。<init>
名字上写着:
At the level of the Java Virtual Machine, every constructor written in the Java programming language (JLS §8.8) appears as an instance initialization method that has the special name
<init>
. This name is supplied by a compiler. Because the name is not a valid identifier, it cannot be used directly in a program written in the Java programming language.
在 Java 虚拟机级别,用 Java 编程语言(JLS §8.8)编写的每个构造函数都作为具有特殊名称 的实例初始化方法出现
<init>
。该名称由编译器提供。由于名称不是有效标识符,因此不能直接在用 Java 编程语言编写的程序中使用。
That's why <init>
can be found on the stack trace, but is not accessible with code.
这就是为什么<init>
可以在堆栈跟踪中找到,但无法通过代码访问的原因。
回答by Stephen C
What is an
<init>
method in Java?
<init>
Java中的方法是什么?
It is a constructor. That's why you get a NoSuchMethodException
when you try to call it as a method.
它是一个构造函数。这就是为什么NoSuchMethodException
当您尝试将其作为方法调用时会得到 a 的原因。
Can it be overriden?
可以覆盖吗?
No.
不。
And if you see a <clinit>
method, that is the classes static initialization "method".
如果你看到一个<clinit>
方法,那就是类静态初始化“方法”。