Why the function "display ()" is automatically placed in the constructor

Here is the following code where I have two classes doing virtually nothing. When the decompiled code "class TestBed" is checked, "int val = tb.display ()" is automatically placed in the constructor. How does this happen?

class TestBed
{
    int display()
    {
        return 100;
    }

    TestBed tb;

    int val = tb.display(); /* will get placed in constructor 
                               automatically. But how? */
}


public class DeleteThis {
    public static void main(String[] args) {
        System.out.println("printing");
    }

}

After decompiling "TestBed.class" using the decompiler, the following code will appear

/* Following is decompiled code */
class TestBed
{

    TestBed tb;
    int val;

    TestBed()
    {
        val = tb.display(); /* How int val = tb.display() gets placed 
                               in constructor automatically */
    }

    int display()
    {
        return 100;
    }
}
+4
source share
6 answers

This is due to the * .class file format. When you compile a * .java file into a * .class file, all instances of the fields that are initialized in the form in which your field var(this:) T myVar = myValuewill be initialized in the constructor code.

:

"", - ( var) ( "" ).

(, var: int val = tb.display();), "code" , .

Java, . 4 ( )

+2

val tb.display. (0 int) . tb.display .

+1

Null Pointer, tb .

, .

,

static TestBed tb;

static int val = tb.display();
+1

, - .

, , , , . .

, val tb.display();.

0

.

0

TestBed tb , int val = tb.display();, . , , , TestBed main(), : -

public class DeleteThis {
   public static void main(String[] args) {
     TestBed tb=new TestBed();
     System.out.println("printing");
    }

nullpointer exception

And the reason you get this code in the decompiler because of this is reading from the java tutorial (could not find the link for javadocs source :))

The Java compiler automatically generates the initialization code for the instance field and places it in the constructor or constructors for the class. The initialization code is inserted into the constructor in the order specified in the source code.

therefore the compiler breaks int val= tb.display()into

int val;

TestBed(){
val=tb.display();
}
0
source

All Articles