类构造函数如何具有相同类的参数?

Par*_*ngh 5 java constructor

当我发现其中一个构造函数将"String"对象作为参数时,我正在查看String.java源代码.这看起来很简单,但我无法消化它.例如:

public class Example {

    private String value;

    public Example() {
        // TODO Auto-generated constructor stub
    }

    public Example(Example e){
        value = e.getValue();
    }

    String getValue() {
        return value;
    }
}
Run Code Online (Sandbox Code Playgroud)

在第一次编译类Example时,编译器会遇到第二个带有'Example'类对象作为参数的构造函数.在这一点上,它将如何找到它,因为它仍在编译这个类?

aio*_*obe 12

编译类时,它需要访问的是类的声明,而不是完整的实现.


换句话说,在编译构造函数时

public Example(Example e) {
    value = e.getValue();
}
Run Code Online (Sandbox Code Playgroud)

它需要知道的是存在一个名为的类Example,并且它有一个方法getValue.在实际尝试编译代码之前,可以在源文件的单独传递中解析此信息.

(顺便说一句,构造函数与方法的工作方式不同.乍一看,在编译任何方法之前,似乎需要编译构造函数,但这种推理会将编译时问题与运行时问题混淆起来.)