There are a number of things wrong with the code that you posted, so that it will not even compile. For example, there is no member variable m1 declared anywhere, yet you are using it in several places (lines 3, 8 and 9). There's also a semi-colon missing on line 7.
So, the code that you posted is not the same as what you are actually running.
Make sure that you post the actual code that you are compiling and running.
Hello again folks. Sorry about the previous mistake and I promise to be more careful with my coding. On that note let's try that question again shall we?
and so once again the output is hi hi followed by an exception. The book says the m2 object's m1 instance variable is never initialized so when m5 tries to use it a NullPointerException is thrown. Does that mean that m2 and m1 are referencing the same object? The third line under the class declaration has an initialization for m1 does it not? I'm also not sure about the dot operator. For example when it connects two references what does that mean exactly? Thanks
I have added some newlines (and a ;), so you can actually read your code.
And I thought, as I went through it, “why has he got an empty constructor? Does he really want m1 to be uninitialised?” I am going to tell you what I told somebody else yesterday:
You need to decide where you do and where you don’t want constructors.
I think you don’t want that empty constructor. You ought not to have m1 uninitialised, but that empty constructor allows that. Delete the empty constructor and force other code to use the other constructor (you might have to change calls to constructors elsewhere), then you won’t have that null any more.
posted 7 years ago
Actually, maybe you do need the empty constructor after all. But that is a bit of bad design, where a class has a field of its own type (a self-referential class), which can become null unexpectedly. I presume your book (by the way: which book?) shows you that code as an example of what can go wrong.
You will have to get a pencil and paper and go through the code writing down what all the references point to. Remember a field starts off pointing to null by default. As you go through the code you will need to rub out the connections and replace them with new connections.
The dot operator (or more precisely the dot separator) separates an object/class/etc from one of its fields/constructors/methods/etc. The two belong together, so fooo.foo() means, “call the foo() method belonging to the object fooo.”