When you create an object of a subclass the constructor of the superclass calls the constructor of the subclass True False?

  • Products
  • Products
    • Coding LMS

      Manage your classroom all in one spot

    • Online IDE

      Write, run & debug code in a web-based IDE

    • CodeHS Pro

      Access a suite of teacher tools & resources

    • Computer Science Curriculum

      6-12th grade courses from intro to AP programming

    • Certifications

      Industry-relevant certifications for students

    • Professional Development

      Online & in-person training for teachers

  • Platform
    • Assignments

      Create & configure your course assignments

    • Classroom

      Manage & organize your class with customizable settings

    • Grading

      Streamline your grading workflow.

    • Data

      Track & analyze student assessments & progress data

    • Write Code

      Write, run, & debug code all in a web-based IDE

    • Integrations

      Connect CodeHS to your district’s educational platform

  • Platform
    • Assignments

      Create & configure your course assignments

    • Classroom

      Manage & organize your class with customizable settings

    • Grading

      Streamline your grading workflow.

    • Data

      Track & analyze student assessments & progress data

    • Write Code

      Write, run, & debug code all in a web-based IDE

    • Integrations

      Connect CodeHS to your district’s educational platform

  • Curriculum
  • Curriculum
    • Course Catalog
    • Pathways
    • AP Courses
    • Elementary
    • States
    • Standards
    • Practice
    • Tutorials
    • Digital Textbooks
  • Professional DevelopmentPD
  • Professional DevelopmentPD
    • Professional Development
    • Online PD Courses
    • In-Person & Virtual Workshops
    • Free PD Events
    • Teacher Certification Prep
    • Microcredentials
  • Online IDE
  • Online IDE
    • Online IDE
    • JavaScript
    • Python
    • Java
    • HTML
    • C++
    • SQL
    • Karel
  • Resources
    • About
    • Privacy Center
    • Case Studies
    • States
    • Testimonials
    • Tweets
    • Read Write Code Blog
    • Coding in the Wild
    • Knowledge Base
    • Student Projects
  • Resources
    • About
    • Privacy Center
    • Case Studies
    • States
    • Testimonials
    • Tweets
    • Read Write Code Blog
    • Coding in the Wild
    • Knowledge Base
    • Student Projects
  • Consider this code:

    class Test { Test() { System.out.println("In constructor of Superclass"); } int adds(int n1, int n2) { return(n1+n2); } void print(int sum) { System.out.println("the sums are " + sum); } } class Test1 extends Test { Test1(int n1, int n2) { System.out.println("In constructor of Subclass"); int sum = this.adds(n1,n2); this.print(sum); } public static void main(String[] args) { Test1 a=new Test1(13,12); Test c=new Test1(15,14); } }

    If we have a constructor in super class, it will be invoked by every object that we construct for the child class (ex. Object a for class Test1 calls Test1(int n1, int n2) and as well as its parent Test()).

    Why does this happen?

    The output of this program is:

    In constructor of Superclass

    In constructor of Subclass

    the sums are 25

    In constructor of Superclass

    In constructor of Subclass

    the sums are 29

    Synesso

    36.4k33 gold badges130 silver badges202 bronze badges

    asked Aug 24, 2011 at 9:13

    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

    answered Aug 24, 2011 at 9:25

    Ashkan AryanAshkan Aryan

    3,5043 gold badges28 silver badges44 bronze badges

    0

    Yes. A superclass must be constructed before a derived class could be constructed too, otherwise some fields that should be available in the derived class could be not initialized.

    A little note: If you have to explicitly call the super class constructor and pass it some parameters:

    baseClassConstructor(){ super(someParams); }

    then the super constructor must be the first method call into derived constructor. For example this won't compile:

    baseClassConstructor(){ foo(); super(someParams); // compilation error }

    answered Aug 24, 2011 at 9:16

    HeisenbugHeisenbug

    38.4k28 gold badges130 silver badges184 bronze badges

    1

    super() is added in each class constructor automatically by compiler.

    As we know well that default constructor is provided by compiler automatically but it also adds super() for the first statement.If you are creating your own constructor and you don't have either this() or super() as the first statement, compiler will provide super() as the first statement of the constructor.

    answered May 18, 2016 at 9:06

    Jaimin PatelJaimin Patel

    4,4113 gold badges31 silver badges35 bronze badges

    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.

    answered Aug 24, 2011 at 9:21

    Oh Chin BoonOh Chin Boon

    22.5k49 gold badges139 silver badges212 bronze badges

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

    answered Aug 24, 2011 at 9:14

    1

    In simple words if super class has parameterized constructor, you need to explicitly call super(params) in the first line of your child class constructor else implicitly all super class constructors are called untill object class is reachead.

    answered Nov 20, 2015 at 6:21

    IshamIsham

    4234 silver badges14 bronze badges

    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...)

    answered Aug 24, 2011 at 9:17

    Andreas DolkAndreas Dolk

    112k18 gold badges175 silver badges262 bronze badges

    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.

    answered Aug 24, 2011 at 9:20

    AlexRAlexR

    113k16 gold badges128 silver badges205 bronze badges

    The base class constructor will be called before the derived class constructor. This makes sense because it guarantees that the base class is properly constructed when the constructor for the derived class is executed. This allows you to use some of the data from the base class during construction of the derived class.

    answered Dec 12, 2012 at 18:02

    RaviRavi

    30.3k41 gold badges115 silver badges168 bronze badges

    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.

    answered May 18, 2013 at 10:59

    Aniket ThakurAniket Thakur

    64.6k37 gold badges270 silver badges284 bronze badges

    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.

    answered Dec 13, 2013 at 6:43

    user1923551user1923551

    4,58634 silver badges29 bronze badges

    Constructor of Super class in called first because all the methods in the program firstly present in heap and after compilation they stores in to the stack,due to which super class constructor is called first.

    answered Jun 30, 2014 at 11:49

    There is a default super() call in your default constructors of sub classes.

    //Default constructor of subClass subClass() { super(); }

    answered Feb 23, 2016 at 5:14

    BhaskarBhaskar

    3155 silver badges21 bronze badges

    "If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem."
    (source: //docs.oracle.com/javase/tutorial/java/IandI/super.html)

    answered Jun 20, 2016 at 8:28

    1

    I'll try to answer this from a different perspective.

    Suppose Java didn't call the super constructor for you automatically. If you inherit the class, you'd have to either call the super constructor implicitly, or rewrite it yourself. This would require you to have internal knowledge of how the super class works, which is bad. It would also require to to rewrite code, which is also not good.

    I agree that calling the super constructor behind the scenes is a little unintuitive. On the other hand, I'm not sure how they could have done this in a more intuitive way.

    answered Sep 8, 2016 at 16:11

    NL3294NL3294

    7281 gold badge8 silver badges20 bronze badges

    As we know that member variables(fields)of a class must be initialized before creating an object because these fields represent the state of object. If these fields are explicitely not initilized then compiler implicitely provides them default values by calling no-argument default constructor. Thats why subclass constructor invokes super class no-argument default constructor or implicitely invoked by compiler .Local variables are not provided default values by compiler.

    answered Nov 27, 2016 at 19:41

    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.

    answered Apr 25, 2017 at 7:40

    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..

    answered Aug 30, 2017 at 18:27

    ShubhamhackzShubhamhackz

    6,4355 gold badges46 silver badges66 bronze badges

    When you create an object of a subclass the constructor of the superclass calls the constructor of the subclass True or false?

    (*2) A subclass constructor always calls the constructor of its superclass, and so on up to the Object constructor, to initialize all the aspects of the instance that the subclass inherits from its superclass.

    Can a subclass constructor call it's superclass constructor?

    A subclass can call a constructor defined by its superclass by use of the following form of super: super(parameter-list); Here, parameter-list specifies any parameters needed by the constructor in the superclass. super( ) must always be the first statement executed inside a subclass constructor.

    When you create any subclass object the subclass constructor executes first and then the superclass constructor executes?

    When you create any subclass object, the subclass constructor must execute first, and then the superclass constructor executes. A nonstatic method cannot override a static member of a parent class. You cannot declare a class to be final.

    How does a subclass constructor call a super class constructor?

    As we know, when an object of a class is created, its default constructor is automatically called. To explicitly call the superclass constructor from the subclass constructor, we use super() .

    Toplist

    Neuester Beitrag

    Stichworte