Java Reference
In-Depth Information
class and the basic syntax for defining a class, instantiating it, and using the result‐
ing object .
The most important thing about classes is that they define new data types. For
example, you might define a class named Point to represent a data point in the two-
dimensional Cartesian coordinate system. This class would define fields (each of
type double ) to hold the x and y coordinates of a point and methods to manipulate
and operate on the point. The Point class is a new data type.
When discussing data types, it is important to distinguish between the data type
itself and the values the data type represents. char is a data type: it represents Uni‐
code characters. But a char value represents a single specific character. A class is a
data type; a class value is called an object . We use the name class because each class
defines a type (or kind, or species, or class) of objects. The Point class is a data type
that represents x,y points, while a Point object represents a single specific x,y point.
As you might imagine, classes and their objects are closely linked. In the sections
that follow, we will discuss both.
a x
Deining a Class
Here is a possible definition of the Point class we have been discussing:
/** Represents a Cartesian (x,y) point */
public class Point {
// The coordinates of the point
public double x , y ;
public Point ( double x , double y ) { // A constructor that
this . x = x ; this . y = y ; // initializes the fields
public double distanceFromOrigin () { // A method that operates
return Math . sqrt ( x * x + y * y ); // on the x and y fields
This class definition is stored in a file named and compiled to a file
named Point.class , where it is available for use by Java programs and other classes.
This class definition is provided here for completeness and to provide context, but
don't expect to understand all the details just yet; most of Chapter 3 is devoted to
the topic of defining classes.
Keep in mind that you don't have to define every class you want to use in a Java
program. The Java platform includes thousands of predefined classes that are guar‐
anteed to be available on every computer that runs Java.
Creating an Object
Now that we have defined the Point class as a new data type, we can use the follow‐
ing line to declare a variable that holds a Point object:
Point p ;
Search WWH ::

Custom Search