Java instance variables initialization with method

前端 未结 6 888
太阳男子
太阳男子 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条回答
  •  萌比男神i
    2021-01-11 10:35

    It's bad practice to use a method in the field initializer. You can fix this by making h final. Then it will be initialized when the class is loaded.

    import java.util.ArrayList;
    
    public class Test {
        int x = giveH();
        final int h=29;
    
        final public int giveH(){
            return h;
        }
    
        public static void main(String args[]) {
            Test t = new Test();
            System.out.print(t.x + " ");
            System.out.print(t.h);          
        }
    }
    

提交回复
热议问题