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

后端 未结 18 1366
误落风尘
误落风尘 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:11

    Since you are inheriting base class properties into derived class, there may be some situations where your derived class constructor requires some of the base class variables to initialize its variables. So first it has to initialize base class variables, and then derived class variables. That's why Java calls first base class constructor, and then derived class constructor.

    And also it doesn't make any sens to initialize child class with out initializing parent class.

提交回复
热议问题