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

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

    Constructor implements logic that makes the object ready to work. Object may hold state in private fields, so only its class' methods can access them. So if you wish instance of your subclass be really ready to work after calling constructor (i.e. all its functionality including inherited from base class is OK) the base class's constructor must be called.

    This is why the system works this way.

    Automatically the default constructor of base class is called. If you want to change this you have to explicitly call constructor of base class by writing super() in the first line of your subclass' constructor.

提交回复
热议问题