Last active
March 16, 2017 09:35
-
-
Save mverleg/0f03c8850c08b264471e690d86a319aa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
For the question, see | |
https://gist.github.com/mverleg/1088fbb5f21590da6691a6e84547bada | |
OUTPUT: | |
super constructor | |
super b | |
x = 1, y = 3 | |
sub b | |
x = null, y = 3 | |
sub constructor | |
super b | |
x = 1, y = 4 | |
sub b | |
x = 2, y = 4 | |
EXPLANATION: | |
SubCls.SubCls: Call the SubCls constructor, which implicitly calls the super-constructor before doing anything else | |
SuperCls.SuperCls: | |
x is initialized as 1 for instances of SuperCls | |
y is initialized as 3 for instances of SuperCls | |
>> "super constructor" | |
SubCls.b: "this" is a SubCls instance, so start searching for "b" at SubCls; which immediately calls super | |
SuperCls.b: | |
>> "super b" | |
unlike methods, attributes are NOT overridden, so x refers to SuperCls.x (which is 1) | |
>> "x = 1, y = 3" | |
SuperCls.b is done, resume running SubCls.b | |
>> "sub b" | |
Perhaps counter-intuitively, "x" is not initialized on SubCls yet. | |
This initialization happens in it's constructor, but that didn't run yet because we're still constructing SuperCls | |
Therefore "x" is null, since that is default for "Integer" (unlike "int") | |
>> "x = null, y = 3" | |
SubCls.b is done, resuming SuperCls.SuperCls | |
SuperCls.SuperCls is done, resuming SubCls.SubCls | |
First, x is initialized as 2 for instances of SubCls | |
This is a "separate" x from SuperCls.x, which is still 1 | |
Only after that, y is overwritten as 4 | |
This DOES refer to the same y; we're not making a new one (no "Integer") | |
>> "sub constructor" | |
SubCls.b: again, "this" is a SubCls, so start at that "b" method | |
SuperCls.b: again, super is called immediately | |
>> "super b" | |
So "x" refers to SuperCls.x (1), which is separate from SubCls.x (2) | |
whereas there is only one "y", which has been assigned value "4" | |
>> "x = 1, y = 4" | |
SuperCls.b is done, resume SubCls.b | |
>> "sub b" | |
This "x" referes to SubCls.x (2); y is unchanged | |
>> "x = 2, y = 4" | |
SubCls.b is done | |
SubCls.SubCls is done, an instance has been made | |
EXTRA: | |
`instance.z` would give a compile error after line 8. | |
`instance` has type SuperCls, so it will only do things a SuperCls could do | |
SuperCls does not have `z` so `instance.z` does not resolve | |
(Even though it's really a SubCls, it acts as a SuperCls) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment