Does object creation of subclass create object of superclass, if yes Is it possible to access it in subclass?

后端 未结 1 1428
别跟我提以往
别跟我提以往 2020-12-18 07:11

My question is if we can access and use indirectly/implicitly created super class objects when we instantiate a subclass .

Lets say ClassA is super cla

相关标签:
1条回答
  • 2020-12-18 07:40

    Since whole inheritance hierarchy gets instantiated when we create a subclass objects, I was wondering, is it possible to access object of class ClassA in client class?

    This is something lot of people get confused. If you create object of subclass, that does not mean it create object of super class.

    Its just a call to constructor of super class, just to ensure that all the required fields are initialized in super class, but this does not create object of super class.

    This question will help you, understanding the concept.

    Check Kevin's answer:

    It doesn't create two objects, only one: B.

    When inheriting from another class, you must call super() in your constructor. If you don't, the compiler will insert that call for you as you can plainly see.

    The superclass constructors are called because otherwise the object would be left in an uninitialized state, possibly unbeknownst to the developer of the subclass.

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