Java Reference
In-Depth Information
To learn about objects we will first examine an existing Java class, and then we will
reimplement our own version of that class from scratch. The
java.awt
package has a
class named
Point
. A
Point
object stores the (
x, y
) coordinates of a position in two-
dimensional space. These coordinates are expressed as integers, although there are
also variations for storing points using floating-point numbers.
Point
objects are
useful for applications that store many two-dimensional locations, such as maps of
cities, graphical animations, and games.
Like most objects,
Point
objects have to be explicitly constructed by calling a
constructor. To construct a specific
Point
object, you have to pass the values you
want for
x
and
y
:
Point p = new Point(3, 8);
After the program executes the previous line of code, you have the following situ-
ation:
p
x 3
x 3 y 8
Once you have constructed a
Point
object, what can you do with it? One of the
most common things you do with an object is print it to the console. A
Point
object,
like many Java objects, can be printed with the
println
statement.
System.out.println(p);
The
println
statement produces the following output. The format is a little ugly,
but it lets you see the
x
and
y
values inside a given
Point
.
java.awt.Point[x=3,y=8]
Point
objects also have a method called
translate
that can be used to shift the
coordinates by a specific delta-x and delta-y, which are passed as parameters. When
you translate a
Point
, you shift its location by the specified amount. For example,
you might say:
p.translate(-1, -2); // subtract 1 from x, subtract 2 from y
Given that the
Point
started out with coordinates (3, 8), this translation would
leave the
Point
with coordinates (2, 6). Thus, after this line of code is executed,
you'd end up with the following situation:
p
x 3
x 2 y 6
Search WWH ::
Custom Search