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 class of SubClassofA
and we instantiate SubClassofA
in a client class ClientClass
using SubClassofA object = new SubClassofA();
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?
If not possible, what might be reasons? Wouldn't it save lots of heap memory if we can access super class objects without recreating those?
I might have misunderstood whole concept of constructor chaining and inheritance hierarchy but please let me know your thoughts on this.
public class ClassA {}
public class SubClassofA extends ClassA {}
public class ClientClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
SubClassofA object = new SubClassofA();
//Above construct means that an instance of super class ClassA exists too
// If we can use those super class instances directly, will it result in memeory saving?
//is it even possible to access implicitly created super class objects tied to subclass?
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With