Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a class constructor has a parameter of the same class?

I was looking into the String.java source code when I found that one of the constructor has "String" object as parameter. This seems simple but I am not able to digest it. For example:

public class Example {

    private String value;

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

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

    String getValue() {
        return value;
    }
}

While compiling class Example for the first time, the compiler would encounter the second constructor with 'Example' class object as parameter. At this point, how will it find it as it is still compiling this class?

like image 480
Paramvir Singh Avatar asked Jul 13 '12 07:07

Paramvir Singh


1 Answers

When the class is compiled, all it needs access to is the declaration of the class, not the full implementation.


Put differently, when compiling the constructor

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

all it needs to know is that there exists a class named Example and that it has a method getValue. This information can be gathered in a separate pass over the source files, prior to actually trying to compile the code.

(Btw, a constructor doesn't work much differently from a method. At first glance it may seem like a constructor needs to be compiled before any method is compiled, but that reasoning mixes up compile-time issues with run-time issues.)

like image 127
aioobe Avatar answered Oct 30 '22 00:10

aioobe