Java Reference
In-Depth Information
25 // translate each point to a new location
26 p1.x += 11;
27 p1.y += 6;
28 p2.x += 1;
29 p2.y += 7;
30
31 // print the points again
32 System.out.println("p1 is (" + p1.x + ", " + p1.y + ")");
33 System.out.println("p2 is (" + p2.x + ", " + p2.y + ")");
34 }
35 }
The code produces the following output:
p1 is (7, 2)
distance from origin = 7.280109889280518
p2 is (4, 3)
distance from origin = 5.0
p1 is (18, 8)
p2 is (5, 10)
The client program has some redundancy that we'll eliminate as we improve our
Point
class in the sections that follow.
Our initial
Point
class essentially serves as a way to group two
int
values into
one object. This technique is somewhat useful for the client program, but the client
could have been written using primitive
int
s instead. Using
Point
objects is not yet
substantially better than using primitive
int
values, because our
Point
objects do
not yet have any behavior. An object that contains state, but no behavior, is some-
times called a
record
or
struct.
In the sections that follow, we'll grow our
Point
class
from a minimal implementation into a proper Java class.
The second version of our
Point
class will contain both state and behavior. Behavior
of objects is specified by writing
instance methods.
The instance methods of an
object describe the messages to which that object can respond.
Instance Method
A method inside an object that operates on that object.
The objects introduced in previous chapters all contained instance methods that
represented their behavior. For example, a
String
object has a
length
method and a
Scanner
object has a
nextInt
method. We think of these methods as being stored
Search WWH ::
Custom Search