Question:
What is printed when the following code is executed?
Answer:
This code will print out 'null'.
This is because the Person constructor is called before the override, meaning that val name is instantiated before the override is called. The default name value is never set because the compiler is clever enough to know we don't wan stringName to be set to "I dont have a name" so it skips that assignment.
Interestingly...
If the stringName was declared with the 'lazy keyword' the code would work properly and print 'Alexandra'. This is because a lazy variable is declared as soon as it is needed, which in this case would be when the name class is instantiated.
No comments:
Post a Comment