Skip to Content
Think Java, 2nd Edition
book

Think Java, 2nd Edition

by Allen B. Downey, Chris Mayfield
November 2019
Beginner
326 pages
6h 44m
English
O'Reilly Media, Inc.
Book available
Content preview from Think Java, 2nd Edition

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, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Head First Java, 2nd Edition

Head First Java, 2nd Edition

Kathy Sierra, Bert Bates
Java in a Nutshell, 8th Edition

Java in a Nutshell, 8th Edition

Benjamin J. Evans, Jason Clark, David Flanagan
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan
The Well-Grounded Java Developer, Second Edition

The Well-Grounded Java Developer, Second Edition

Benjamin Evans, Martijn Verburg, Jason Clark

Publisher Resources

ISBN: 9781492072492Errata PageSupplemental Content