Chapter 10. Mutable Objects
As you learned in the previous chapter, an object is a collection of data that provides a set of methods. For example, a String
is a collection of characters that provides methods like charAt
and substring
.
This chapter explores two new types of objects: Point
and Rectangle
. You’ll see how to write methods that take objects as parameters and produce objects as return values. You will also take a first look at the source code for the Java library.
Point Objects
In math, 2D points are often written in parentheses with a comma separating the coordinates. For example, indicates the origin, and indicates the point x units to the right and y units up from the origin.
The java.awt
package provides a class named Point
that represents a location in a Cartesian plane. In order to use the Point
class, you have to import it:
import
java.awt.Point
;
Then, to create a new point, you use the new
operator:
Point
blank
;
blank
=
new
Point
(
3
,
4
);
The first line declares that blank
has type Point
. The second line creates the new Point
with the coordinates and . The result of the new
operator is a reference to the object. Figure 10-1 shows the result.
As usual, the name of the variable blank
appears outside the box, and its value appears inside the box. In this case, the value is a reference, ...
Get Think Java, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.