Example 1
If we are creating a class Car, we might want to have fields to keep track of
fuel consumption rate, distance travelled, and price of gasoline. The first
two fields will vary from one car to another and should therefore be instance
fields. If all cars in the class use the same grade of gasoline, the price will be
the same for all cars. Consequently, there is no point in keeping a separate
copy of the price of gas for every Car object. Instead, we keep it as a class
field so that there is only one copy for the entire class. The declarations of
these fields might take the following form.
class Car
{
private double consumptionRate;
private double distance;
private static double gasPrice;
}
|