Java Reference
In-Depth Information
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 topic.
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 cre-
ates 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 de-
clares 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 ob-
jects. 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.
 
 
Search WWH ::




Custom Search