The "how" of an object is defined by its class, which defines the implementation of the methods the object
supports. Each object is an instance of a class. When a method is invoked on an object, the class is examined
to find the code to be run. An object can use other objects to do its job, but we start with simple classes that
implement all their own methods directly.
2.1. A Simple Class
Here is a simple class, called Body[1] that could be used to store data about celestial bodies such as comets,
asteroids, planets, and stars:
[1] Good naming is a key part of class design, and Body should really be called
CelestialBody or something of that kind. We use Body for brevity, as we refer to it
dozens of time throughout the book.
class Body {
public long idNum;
public String name;
public Body orbits;
public static long nextID = 0;
}
A class is declared using the keyword class, giving the class a name and listing the class members between
curly braces. A class declaration creates a type name, so references to objects of that type can be declared with
a simple
Body mercury;
This declaration states that mercury is a variable that can hold a reference to an object of type Body. The
declaration does not create an objectit declares only a reference that is allowed to refer to a Body object.
During its existence, the reference mercury may refer to any number of Body objects. These objects must
be explicitly created. In this respect, the Java programming language is different from languages in which
objects are created when you declare variables.
This first version of Body is poorly designed. This is intentional: We will demonstrate the value of certain
language features as we improve the class in this chapter.
2.1.1. Class Members
A class can have three kinds of members:
Fields are the data variables associated with a class and its objects and hold the state of the class or
object.
•
- Methods contain the executable code of a class and define the behavior of objects.
Nested classes and nested interfaces are declarations of classes or interfaces that occur nested within
the declaration of another class or interface.
•
In this chapter we concentrate on the basic members: fields and methods. Nested members are discussed in
Chapter 5.