Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Java
Memory Space Allocation and subclasses
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Chris Uppal, post: 552775"] The way it works is that given: class Base { String baseExplicit = "Step1"; String baseOther; Base() { baseOther = "Step2"; } } class Derived { String derivedExplicit = "Step3"; String derivedOther; Derived() { derivedOther = "Step4"; } } The various variables are initialised in the order implied by the "Step X" values. I.e. When a Derived is created, first the store is allocated and set to the default values of the fields (nulls in this case), then the Derived constructor is called. This method's first step is to invoke the superclass constructor which will first set baseExplicit, and then start executing the body of that constructor, thus setting baseOther. Then control returns to the Derived constructor; it will set derivedExplicit, and then start executing the code you supplied, and so derivedOther will be set last of all. I.e. the compiler insetrs code for implementing explicit initialisation after the call to the superclass constructor and before the "real" body of the constructor. That means that during the execution of a superclass constructor, any methods that are called in the derived class (i.e. which override some method in the base) will see the default values of any explicitly initialised fields. Which can be unexpected... <Advanced note> There are a couple of subtleties. One is that int/String/boolean/char fields declared final and initialised to a constant, are inlined by the compiler, so code in the derived class will always "think" it's seeing the explicitly initialised value, even if it is invoked from the superclass constructor. The other is that inner classes have an implicit "hidden" field that refers to their outer object; that (following the above logic) would not be set until after the inner class's parent constructor had completed; however that behaviour would break the intended semantics of inner classes so starting with JDK 1.4 (apparently it required a change to the verifier) the synthetic "outer" field is supposed to be set before the superclass constructor is called. </Advanced note> I'm not absolutely sure that I'm answering your question here, but HTH anyway... -- chris [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Java
Memory Space Allocation and subclasses
Top