Default initialization of private fields in Java

Suppose I have a class named person:

class Person{
    private int num = 1;
}

When calling an empty constructor for the person class, will Java initialize num to the default value of zero and then assign num to 1? Or will Java immediately initialize num to 1? Will C not execute the former unless initialization syntax is used?

thank you!

Solution

It will first be assigned to zero

If you put something before the field declaration, you can see:

class Person{
    { print(); }
    private int num = 1;
    { print(); }

    void print() {
      System.out.println(num);
    }
}

This will print:

0
1

This is in JLS sec 4.12 Description in 5:

Sec 15.9. 4 (key supplement, part omitted):

In other words, object creation and constructor call are different operations, and the field is initialized to its default value before calling the constructor

The actual field initialization occurs in the constructor: the field initialization is inline to each constructor that calls super (...) immediately after calling super (...) The following are identical to the above:

class Person{
   private int num;

   Person() {
     super();
     print();
     num = 1;
     print();
   }

   void print() {
     System.out.println(num);
   }
}

A subtle point, although declaring the field final will produce the output of this Code:

1
1

This does not mean that the final variable will be initialized earlier In this case, all that changes is that num has become a compile - time constant expression, so it is inlined Therefore, print () will actually execute:

System.out.println(1);

In other words, it does not read the field at all

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>