Who provides the default constructor in Java? Compiler or JVM?

Pure'ajax :

Is the constructor added at run-time or compile time?(I guess it is compile time). I need some in depth explanation please, at JVM architecture level.

I read various articles.. some says compiler.. and others say JVM. I want to be very much sure(proofs will help a lot).

Sorry if the question is stupid(am still digesting the terminologies)!!!

Thanks in advance.

Edwin Dalorzo :

For a formal reference, the nature of the default constructor is explained in both:

Alternatively, if you're using Oracle JDK or OpenJDK, you could easily demonstrate this behavior to verify that it is the compiler the one that does all the magic.

All you need to do is to use the Java decompiler tool that comes with your JDK to see what bytecodes are being generated in your class files.

You should see an executable named javap under $JDK_HOME/bin/

If you had a simple file like Demo.java containing just one class, e.g.

public class Demo {}

And you compile it using the command javac Demo.java, and then you run the decompiler using javap -c Demo, the output should say something like:

Compiled from "Demo.java"
public class Demo {
  public Demo();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return
}

Which demonstrates that it is the compiler which adds the default constructor, since it was not in your source code but it is indeed in your compiled class file.

You will also notice that the constructor access level matches that of the class for which it was generated. So, if you do

public class Demo { 
  protected static class Other {}
}

And you compile that, and then do a javap -c Demo.Other you get

public class Demo$Other {
  protected Demo$Other();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return
}

Once more, demonstrating that the compiler adds a default constructor matching the accessibility of the class for which it was generated as the specifications above say it should do.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=464467&siteId=1
Recommended