You can follow this issue in YouTrack under KT-10455. If you squint, you’ll see a faint squiggly underline in IDEA when you use this in a constructor. Of the three issues I’ve mentioned, this is the only one that currently generates any kind of warning. If the function or property is non-final, it can end up executing code in a subclass before the subclass properties have been initialized. Using any function or property of the current class is effectively a reference to this. But you don’t need to explicitly use the word this to run into the problem. The this keyword refers to the current object, and inside the constructor it goes without saying that the current object is still in the middle of being constructed. It shouldn’t be surprising that using this in a constructor can have strange behaviour. The greeting property doesn’t have a value, because it hasn’t been initialized yet. But at the moment when toString is called, we’re still in the middle of initialising the Greeter superclass. That function is overridden by the concrete Hello subclass, and its implementation tries to access the greeting property. In the Greeter example, the call to println implicitly calls toString on the current object. Once that’s done, initialization proceeds down the object’s class hierarchy, filling in the properties of each class in order. When you create a new object, its topmost superclass is initialized first. The definitive guide to handling null by Anirban Chatterjee The Startup Medium 500 Apologies, but something went wrong on our end. The problem exists there too, and it has to do with the order that classes and their properties are initialized. This might be the most counterintuitive of the three issues, but it’s probably also the most familiar to anyone who’s worked with Java. In reality, it throws a NullPointerException.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |