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

后端 未结 18 1309
误落风尘
误落风尘 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 19:48

    When we create an object of subclass, it must take into consideration all the member functions and member variables defined in the superclass. A case might arise in which some member variable might be initialized in some of the superclass constructors. Hence when we create a subclass object, all the constructors in the corresponding inheritance tree are called in the top-bottom fashion.

    Specifically when a variable is defined as protected it will always be accessible in the subclass irrespective of whether the subclass is in the same package or not. Now from the subclass if we call a superclass function to print the value of this protected variable(which may be initialized in the constructor of the superclass) we must get the correct initialized value.Hence all the superclass constructors are invoked.

    Internally Java calls super() in each constructor. So each subclass constructor calls it's superclass constructor using super() and hence they are executed in top-bottom fashion.

    Note : Functions can be overridden not the variables.

    0 讨论(0)
  • 2020-11-27 19:49

    Parents Exits First!! And like real world Child Can't exist without the Parents.. So initialising parents(SuperClass) first is important in order to use thrm in the children(Subclass) Classes..

    0 讨论(0)
  • 2020-11-27 19:51

    here your extending Test to your test1 class meaning u can access all the methods and variable of test in your test1. keep in note that u can access a class methods or variable only if memory is allocated to it and for that it need some constructor either a default or parameterized ,so here wen the compiler finds that it is extending a class it will try to find the super class constructor so that u can access all its methods.

    0 讨论(0)
  • 2020-11-27 19:52

    That´s how Java works. If you create a child object, the super constructor is (implicitly) called.

    0 讨论(0)
  • 2020-11-27 19:52

    The subclass inherits fields from it's superclass(es) and those fields have to get constructed/initialised (that's the usual purpose of a constructor: init the class members so that the instance works as required. We know that some people but a lot more functionality in those poor constructors...)

    0 讨论(0)
  • 2020-11-27 19:54

    Because it will ensure that when a constructor is invoked, it can rely on all the fields in its superclass being initialised.

    see 3.4.4 in here

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