| Author |
Using THIS
|
Rich Nelson
Greenhorn
Joined: Sep 22, 2007
Posts: 15
|
|
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?
|
 |
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
|
|
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
|
 |
Rich Nelson
Greenhorn
Joined: Sep 22, 2007
Posts: 15
|
|
|
That's a great way of explaining it, thanks alot.
|
 |
Rich Nelson
Greenhorn
Joined: Sep 22, 2007
Posts: 15
|
|
So would this be correct?
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16680
|
|
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. Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
|
|
Ah, that would be a much more valuable lesson indeed.
|
 |
Martha Cofran
Greenhorn
Joined: Jan 31, 2001
Posts: 11
|
|
Why not do both to make sure you've met your instructors expectations? public class X { private int a, b, c; public X() { this(0); } public X(int n) { this(n, n); } public X(int n, int m){ this(n, m, 1); } public X(int n, int m, int p){ this.a = n; this.b = m; this.c = p; } }
|
 |
 |
|
|
subject: Using THIS
|
|
|