Why can my instance initializer block reference a field before it is declared?

后端 未结 5 508
無奈伤痛
無奈伤痛 2021-01-18 03:19

My understanding is that you cannot reference a variable before it has been declared, and that all code (including instance initializers) that is within the body of a class,

5条回答
  •  借酒劲吻你
    2021-01-18 04:16

    The order of declaration is not important. You could also write:

    public  class WhyIsThisOk {
    
        {
            a = 5;
        }
    
        public WhyIsThisOk() {
        }
    
        public static void main(String[] args) {
            System.out.println(new WhyIsThisOk().a);
        }
    
        int a = 10;
    }
    

    Important is, that the compiler copies (top down) first a=5 and then a=10 into constructor so it looks like:

    public WhyIsThisOk() {
        a = 5;
        a = 10;
    }
    

    Finally look at this example:

    public class WhyIsThisOk {
    
        {
            a = get5();
        }
    
        public WhyIsThisOk() {
            a = get7();
        }
    
        public static void main(String[] args) {
            System.out.println(new WhyIsThisOk().a);
        }
    
        int a = get10();
    
        public static int get5() {
            System.out.println("get5 from: " + new Exception().getStackTrace()[1].getMethodName());
            return 5;
        }
    
        public static int get7() {
            System.out.println("get7 from: " + new Exception().getStackTrace()[1].getMethodName());
            return 7;
        }
    
        public static int get10() {
            System.out.println("get10 from: " + new Exception().getStackTrace()[1].getMethodName());
            return 10;
        }
    }
    

    Output is:

    get5 from: 
    get10 from: 
    get7 from: 
    7
    

提交回复
热议问题