Default variables' values vs initialization with default

前端 未结 1 1369
别那么骄傲
别那么骄傲 2020-12-16 11:44

We all know, that according to JLS7 p.4.12.5 every instance variable is initialized with default value. E.g. (1):

public class Test {
    private Integer a;          


        
1条回答
  •  有刺的猬
    2020-12-16 12:14

    No, they're not equivalent. Default values are assigned immediately, on object instantiation. The assignment in field initializers happens when the superclass constructor has been called... which means you can see a difference in some cases. Sample code:

    class Superclass {
        public Superclass() {
            someMethod();
        }
    
        void someMethod() {}
    }
    
    class Subclass extends Superclass {
        private int explicit = 0;
        private int implicit;
    
        public Subclass() {
            System.out.println("explicit: " + explicit);
            System.out.println("implicit: " + implicit);
        }
    
        @Override void someMethod() {
            explicit = 5;
            implicit = 5;
        }
    }
    
    public class Test {
        public static void main(String[] args) {
            new Subclass();
        }
    }
    

    Output:

    explicit: 0
    implicit: 5
    

    Here you can see that the explicit field initialization "reset" the value of explicit back to 0 after the Superclass constructor finished but before the subclass constructor body executed. The value of implicit still has the value assigned within the polymorphic call to someMethod from the Superclass constructor.

    0 讨论(0)
提交回复
热议问题