Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

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

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?


    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...