Default constructor does not initialize the instance members of the class?

前端 未结 7 2460
清酒与你
清酒与你 2021-02-13 03:05

I encountered a question that asks \"Which of the following are true about the \"default\" constructor?\"

and an option \"It initializes the instance members of the cla

7条回答
  •  情歌与酒
    2021-02-13 03:33

    In Java fields are initialized before the constructor. This can be easily proved by the following code:

    public class MyClass {
    
        int myField = initMyField();
    
        MyClass(){
            System.out.println("ctor");
        }
    
        static int initMyField() {
            System.out.println("init field");
            return 1;
        }
    }
    

    output

    init field
    ctor
    

    You can also check the de-compiled code.

提交回复
热议问题