Chapter 10. Objects

As we 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.

Java is an “object-oriented” language, which means that it uses objects to represent data and provide methods related to them. This way of organizing programs is a powerful design concept, and we will introduce it a little at a time throughout the remainder of the book.

In this chapter, we introduce two new types of objects: Point and Rectangle. We show how to write methods that take objects as parameters and produce objects as return values. We also take a look at the source code for the Java library.

Point Objects

The java.awt package provides a class named Point intended to represent the coordinates of a location in a Cartesian plane. In mathematical notation, 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.

In order to use the Point class, you have to import it:

import java.awt.Point;

Then, to create a new point, you have to use the new operator:

Point blank;
blank = new Point(3, 4);

The first line declares that blank ...

Get Think Java 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.