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, (0,0) indicates the origin, and (x,y) 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 x=3 and y=4. The result of the new operator is a reference to the object. Figure 10-1 shows the result.

Figure 10-1. Memory diagram showing a variable that refers to a Point object

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.