|
Example 1: The Car Class
| |||
|
Suppose you need to write a traffic simulation program that watches cars going past an intersection. Each car has a speed, a maximum speed, and a license plate that uniquely identifies it. In traditional programming languages you'd have two floating point and one string variable for each car. With a class you combine these into one thing like this.
These variables (licensePlate, speed
and maxSpeed) are called the member variables,
instance variables, or fields of the class.
Fields tell you what a class is and what its properties are. An object is a specific instance of a class with particular values (possibly mutable) for the fields. While a class is a general blueprint for objects, an instance is a particular object. Note the use of comments to specify the units. That's important. A unit confusion between pounds and newtons led to the loss of NASA's $94 million Mars Climate Orbiter. (Believe it or not that's a cheap mission by NASA standards. If you're rich enough that you don't have to worry about losing $94 million worth of work, you don't have to put comments in your source code. Everybody else has to use comments.) How would you write an Class Angle{ String Name;
//e.g.
"angle 1 or angle 2" } | |||
|
| |||