Re: reserved word "this"


[ Follow Ups ] [ Post Followup ] [ WWWBoard for 308-203A ] [ FAQ ]

Posted by Jacob Eliosoff on September 28, 19100 at 20:20:07:

In Reply to: reserved word "this" posted by Caroline Viger on September 27, 19100 at 22:28:46:

: I don't understand why an object would want to refer to
: itself (that's what "this" is for... right?) For
: example, in UserIO, what does:
: protected UserIO()
: {
: this (System.in, System.out);
: }
: do?
: Thanks Caroline

The form "this(x, y)" is a special syntax
which can only be used in constructors (UserIO()
above is a constructor). It means, "call the
other constructor which takes these arguments."
So, if the user calls "new UserIO()" with no
parameters, by default a UserIO object will be
constructed as if they had called
"new UserIO(System.in, System.out)". In other
words, the default streams to read and write to
are System.in and System.out.
The "this" variable has other uses. For
example, sometimes in a method you have a local
variable and an instance variable with the same
name, and the "this." prefix can be used to
identify the instance variable. So you might see
code like this:

class Point {
/* Two instance vars to store coords: */
int x, y;

/* Construct a new Point with the given coords
(note that the parameters have the same
name as the instance variables). */
public Point(int x, int y) {
/* Set the instance variables from the
arguments: */
this.x = x;
this.y = y;
}
}

-Jacob



Follow Ups:



Post a Followup

Name:
E-Mail:

Subject:

Comments:

Optional Link URL:
Link Title:
Optional Image URL:


[ Follow Ups ] [ Post Followup ] [ WWWBoard for 308-203A ] [ FAQ ]