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 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 |