Java instance variables initialization with method

前端 未结 6 930
太阳男子
太阳男子 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:32

    Compilation in Java doesn't need the method to be declared before it is used. The Java tutorial goes into a bit more detail on initialization.

    Here's a way to think about it: the compiler will make a note to look for a method called giveH somewhere in scope, and it will only error if it leaves the scope and doesn't find it. Once it gets to the giveH declaration then the note is resolved and everyone is happy.

    Also, the variable initialization for instance variables in Java is moved to the beginning of the constructor. You can think of the lines above being split into two parts, with the declaration for x and h above, and the assignment inside the constructor.

    The order of declaration does matter in this case. When the variable x is initialized, h has the default value of 0, so giveH() will return that default value. After that, the variable h is given the value 29.

    You can also look at the Java Language Specification sections on Field Initialization and Forward References During Field Initialization.

提交回复
热议问题