Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - Does an instance of superclass get created when we instantiate an object?

Does an instance of superclass get created when we instantiate a particular class in java. If that is the case then there would be a lot of overhead of instantiating all the super classes. I tried following code:

public class AClass {
    public AClass() {
        System.out.println("Constructor A");
    }
}

public class BClass extends AClass{
    public BClass(){
        System.out.println("Constructor B");
    }
}

public class Test {
    public static void main(String[] args) {
        BClass b = new BClass();
    }
}

The output of the code is :

Constructor A

Constructor B

So, does it mean that the complete hierarchy of the objects of the superclasses get created when we instantiate a class?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

A single object is created - but that object is an instance of both the superclass and the subclass (and java.lang.Object itself). There aren't three separate objects. There's one object with one set of fields (basically the union of all the fields declared up and down the hierarchy) and one object header.

The constructors are executed all the way up the inheritance hierarchy - but the this reference will be the same for all of those constructors; they're all contributing to the initialization of the single object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...