Why is constructor of super class invoked when we declare the object of sub class? (Java)

后端 未结 18 1410
误落风尘
误落风尘 2020-11-27 19:30

Consider this code:

class Test {
    Test() {
        System.out.println(\"In constructor of Superclass\");
    }

    int adds(int n1, int n2) {
        ret         


        
18条回答
  •  不知归路
    2020-11-27 20:05

    Java classes are instantiated in the following order:

    (at classload time) 0. initializers for static members and static initializer blocks, in order of declaration.

    (at each new object)

    1. create local variables for constructor arguments
    2. if constructor begins with invocation of another constructor for the class, evaluate the arguments and recurse to previous step. All steps are completed for that constructor, including further recursion of constructor calls, before continuing.
    3. if the superclass hasn't been constructed by the above, construct the the superclass (using the no-arg constructor if not specified). Like #2, go through all of these steps for the superclass, including constructing IT'S superclass, before continuing.
    4. initializers for instance variables and non-static initializer blocks, in order of declaration.
    5. rest of the constructor.

提交回复
热议问题