This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hello, I have a homework assignment which prompts me to use the following code...
...and re-write these constructors using the "this" reference. I can't seem to grasp the concept of using "this", however. Could someone please explain what needs to be done here, and give me an example of how I could solve at least one of these methods in this way?
Sometimes I like to think of object instances as people. The code in the class is a set of instructions the person must follow. Imagine I round up a person to act as an object and I hand him a hat and say "put on this hat". He's probably going to assume I mean put it on his own head. But maybe he's sitting next to somebody who really needs a hat, and he puts it on their head. Then I'd clarify the instructions "put this hat on your own head" Now he can't make that mistake.
When the code is running, "this" is a lot like "your own". In your class, you're assigning a value to "a". The object looks around and the only "a" it can see is its own variable, so there's no question what you mean. You can still write the code to say "your own a" even if it's not really necessary.
So when is it necessary? When there might be some confusion about which "a" we mean. This is common in constructors:
Read up on visibility and scoping to see what the compiler would think if you left "this" out of that constructor. Find out if "this" is necessary or just a favor for future readers?
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
I would recommend that you ask your instructor to clarify the assignment a bit more. Based on the number of constructors, and how many are just variations of others... you instructor could also be talking about using the this() syntax to have your constructors call each other.