0

People say that there are some codes in Java that are mandatory even if the programmer doesn't write them. Java compiler writes it by itself implicitly.

Like my code is this

class Test {

    public static void main(String args[]) {
        Test obj = new Test();
    }
}

I have not written a default constructor here, that means the Java compiler will write it implicitly by itself.

That means my Test.class file has a default constructor in it.

And if I decompile my Test.class file it should look like this

class Test {

    Test() {
        super();
    }

    public static void main(String args[]) {
        Test obj = new Test();
    }
}

Why is it not showing any default constructor in my java file when I'm decompiling?

HoRn
  • 1,458
  • 5
  • 20
  • 25
  • Decompilers are not perfect tools for learning what a compiler does, because they *know* and react to some of those implicit decisions. If you want to know what exactly a Java compiler does, you should get familiar with the output of the `javap` command which shows you at a rather low level what exactly a .class file contains (especially when invoked using `-v`). – Joachim Sauer Oct 14 '21 at 19:30

1 Answers1

1

Your decompiler may not necessarily show a default ctor because it is aware of the implicitness of it. This is a design decision on the part of the implementor of that compiler, and might be configurable with some setting.

However, it's clearly present as bytecode - compiling the following java code:

class A {}

and then disassembling it with javap -c A.class shows a default constructor:

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

Of course, it does nothing but load this, push it to the stack, and then invoke the no-arg superclass ctor.

nanofarad
  • 40,330
  • 4
  • 86
  • 117