Java: object initialization sequence

There is code that is set as a task for junior Java developers. I have been using Java for five years, and this piece of code is completely confusing to me:

public class Main {

    String variable;

    public static void main(String[] args) {
        System.out.println("Hello World!");
        B b = new B();
    }

    public Main(){
        printVariable();
    }

    protected void printVariable(){
        variable = "variable is initialized in Main Class";
    }
}

public class B extends Main {

    String variable = null;

    public B(){
        System.out.println("variable value = " + variable);
    }

    protected void printVariable(){
        variable = "variable is initialized in B Class";
    }
}

The output will be:

Hello World!
variable value = null

But if we change String variable = null;to String variable;, we get:

Hello World!
variable value = variable is initialized in B Class

The second conclusion is more clear to me. So, as far as I know the initialization sequence in Java, for example:

  • We go to the root of the class hierarchy (for Java, it is always the Object class) when we come to this root parent class:
    • All static data fields are initialized;
    • All static field initializers and static initialization blocks are executed;
    • All non-static data fields are initialized;
    • All non-static field initializers and non-static initialization blocks are executed;
    • :
  • .

, this -

, , ​​:

  • B;
  • part Main;
  • main.variable null;
  • Main;
  • b.printVariable() Main; ( main.printvariable? this .)
  • field b.variable " B-"
  • B;
  • b.variable , ?;
  • B

, - , . String variable = null; String variable; .

+5
3

:

  • → ""
  • → B()
  • B() → Main() → b.printVariable() →
  • B, = null.

, Main() B. , = null . , B Main.

java- , , .

+9

-, , , variable = null;. . .

, , class B printVariable() . printVariable() B.

, variable = null, B. Main(), printVariable(). , variable=null, variable.

, variable=null, variable, printVariable(), , , .

, , new B():

Main()     //super constructor
  B#printVariable()
  initializtion of variables in B constructor (if any) [i.e. variable=null, if present]
+2

! , . . , , Main:

public Main(String something){
 printVariable();
}

If the person answers what happens, remove the argument and ask the original questions. If a person does not answer - there is no need to continue - he / he is the youngest.

You can also remove the protected qualifier in class B and ask what happens if you have a goal not to hire this person :)

+1
source

All Articles