Originally posted by Mike Doss:
I am relatively new to OOP and have a question on constructors:
1) Do constructors actually "construct" the object in memory, or does it merely initialize the state of instance variables? I am under the impression that the "new" keyword actually "constructs" your object, and that the constructor is just a convenience that allows you to initialize the state of that object at the time of instantiation. However, a C++ book I skimmed mentioned in passing that a C++ constructor serves additional purpose other than mere intialization-- if this is also true for Java, I do not know. This leads me to my second question...
2) Why must a child call the parent's constructor-- super() -- at the FIRST LINE of its own constructor? I thought it might have to do with some kind of structural layering of objects (building from the top layer down), but if constructors in fact merely initialize the states of instance variables, it would seem unnecessary to require to have that first-line requrement.
Much thanks...
The new creates all the instance variables for each class up the chain starting at the top and working its way down. In the process, it runs the constructor code for each object starting at the top and working its way down. Let's take a simple example.
So even if all that is happening is instance variable initialization, order does matter.
So why must super be called first? Because ClassB is accessing a variable (and may run methods) that only exist in ClassA so the variables need to be allocated and the class loaded into memory before ClassB can do anything.
As to the first question, there is more to the "new" than just initializing variables. The class must be loaded by the ClassLoader in order to be interpreted into machine language instructions.