How are fields initialized by the default constructor

pyskmr :

As many of the authors have written in their books that the default values of instance variables inside a class are initialized by the class-default constructor, but I have an issue understanding this fact.

class A {
    int x;

    A() {}
}

As I have provided the default constructor of class A, now how the value of x is initialised to 0?

Zabuza :

Explanation

As written in the JLS, fields are always automatically initizialized to their default value, before any other assignment.

The default for int is 0. So this is actually part of the Java standard, per definition. Call it magic, it has nothing to do with whats written in the constructor or anything.

So there is nothing in the source code that explicitly does this. It is implemented in the JVM, which must adhere to the JLS in order to represent a valid implementation of Java (there are more than just one Java implementations).

See §4.12.5:

Initial Values of Variables

Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2)


Note

You can even observe that this happens before any assignment. Take a look at the following example:

public static void main(String[] args) {
    System.out.println("After: " + x);
}

private static final int x = assign();

private static int assign() {
    // Access the value before first assignment
    System.out.println("Before: " + x);

    return x + 1;
}

which outputs

Before: 0
After: 1

So it x is already 0, before the first assignment x = .... It is immediatly defaulted to 0 at variable creation, as described in the JLS.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=164106&siteId=1