Java instance variables initialization with method

前端 未结 6 874
太阳男子
太阳男子 2021-01-11 09:43

I am a little bit confused about the following piece of code:

public class Test{

  int x = giveH();
  int h = 29;

  public int giveH(){
     return h;
  }
         


        
6条回答
  •  無奈伤痛
    2021-01-11 10:33

    @Maloubobola has provided the correct answer, but since you don't seem to fully understand yet, let me try to elaborate.

    When Test is created, it runs the variable initialization (x = giveH(), h= 29) once. Your misunderstanding may be that variable x is always determined by giveH(), whereas it only determines it's value when x is initialized.

    That's why the order of the statements is crucial here; x is initialized before h, and therefore h is 0 when giveH() is called at x's initialization.

提交回复
热议问题