Function initializes

Look at the code

class Parent {
    int i = 1;
    Parent() {
        System.out.println(i);
        int x = getValue();
        System.out.println(x);
    }
    {
        i = 2;
    }//这个叫构造块
    protected int getValue() {
        return i;
    }
}

class Son extends Parent {
    int j = 1;
    Son() {j = 2;}
    protected int getValue() {return j;}
}
class Test {
    public static void main(String[] args) {
        Son son = new Son();
        System.out.println(son.getValue());
    }
}

I thought the above code output is 1,1,2.
The reason is: when new son, will first initialize the parent, parent i will initially assigned 1, and then execute the constructor, output 1; then continue to go down, getvalue get 1 and output 1, 2 and finally i assignment. Then son.getValue () time, j = 2 this will be the first executed in the constructor. Therefore, the final output 2.

But the reality is that: when parent initialize, execute building blocks, i is assigned 2, and then outputs 2; getvalue then call when the call is getvalue son, at this time no initialization j, j = 0. Last call son.getValue () time, son has been initialized, output 2 .. So the normal result is 2,0,2.

Here it comes to knowledge blind spot is to say: if the child class overrides the parent class, then in the constructor, method calls also subclass.

There is also a piece of code

// 程序B
public class MagimaTest {
    public static void main(String[] args) {
        magimaFunction();
    }
    static MagimaTest st = new MagimaTest();
    static {
        System.out.println("1");
    }
    {
        System.out.println("2");
    }
    MagimaTest() {
        System.out.println("3");
        System.out.println("a=" + a + ",b=" + b);
    }
    public static void magimaFunction() {
        System.out.println("4");
    }
    int a = 110;
    static int b = 112;
}

I thought output is:
. 1
. 4
. 3
A = 0, B = 112

But in fact it is:
2
. 3
A = 110, B = 0
. 1
. 4

Before performing the main, you need to initialize MagimaTest class.
To perform static MagimaTest st = new MagimaTest () ;
then the constructor is executed, but before the constructor is executed before starting. 2. At this time, the output of
initializing a
and the constructor is executed, when a = 110, b is not initialized. Output 3; a = 110, b = 0.
Then st member variable initialization is complete, the next one static. 1. output
next continue to initialize a static variable b
last call magimaFunction output 4.

Performing static MagimaTest st = new MagimaTest ();, the following are not initialized static, complete the first configuration step MagimaTest. Accordingly assignment will be in front of a b.

Guess you like

Origin blog.csdn.net/huqianlei/article/details/91488254