This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
Does JVM automatically also create an instance of class A ? By rule, it automatically calls super class' constructor, so it seems it should also create an instance of A in addition to an instance of "Sub". So it creates two different instances in memory after I do "Sub sub = new Sub()" ?
Ernest Friedman-Hill wrote:An instance of Sub contains an instance of A, like a mango contains a pit. They're not separate objects.
Please be more specific if you don't mind --
1. So there is only ONE object got created, right ?
2. What do you mean "object of Sub contains an instance of A" ? A is not a class variable of Sub, how does it "contain" ? Does "sub" object contain a reference to "A" ? wait, since there is not a separate object creatd for A, there should not be such reference at all. So what do you mean by "contain an instance of A". Please help clarify.
author and iconoclast
As I said before, a "Sub" contains an "A" exactly the way a mango contains a pit. The pit is part of the mango; it's inside. There's a part of the mango you can call "the pit", but in reality it's it's all one object, the mango including the pit.
1) Yes, one object.
2) Imagine that "Sub" declares one "int" member variable, and "A" has one "int" member variable. Then an instance of "Sub" is the size of two "int" member variables. Part of the memory that makes up the Sub object is taken up by the "A" part -- one of the ints.