University of Toronto - Summer 2001
Department of Computer Science
Week 2 - Class Example
Sports Car Example
Java program
// SportsCar: this class models a sports car.
class SportsCar {
private String colour; // colour of car
private int amtGas; // litres of gas in tank
private int odometer; // current odometer reading in kms
private double fuelConsumption; // fuel consumption in km/L
/*
* SportsCar constructor: create a new sports car that has
* colour 'startColour' and fuel consumption in km/L
* of 'consumption.'
*/
public SportsCar (String startColour, double consumption) {
colour = startColour;
fuelConsumption = consumption;
}
/*
* fill: this method is used to fill up the car with
* 'fillAmount' litres of gas.
*/
public void fill (int fillAmount) {
amtGas = amtGas + fillAmount;
}
/*
* drive: this method is used to drive the car for
* 'distance' kms.
*/
public void drive (int distance) {
odometer = odometer + distance;
amtGas = amtGas - (int)(distance/fuelConsumption);
}
/*
* report: this method prints out information about the
* current state of this sports car.
*/
public void report () {
System.out.println ("Colour: " + colour);
System.out.println ("Gas: " + amtGas + " litres");
System.out.println ("Odometer: " + odometer + " km");
System.out.println ("Fuel Consumption: " + fuelConsumption +
" km/litre");
}
}
// Drive: This program simulates the driving of two sports cars.
public class Drive {
public static void main (String[] args) {
// Create sports car for Dale Earnhardt.
SportsCar earnhardt = new SportsCar ("red", 15.5);
// Fill car with 50 litres of gas, drive 200 kms, then
// fill with 10 more litres of gas and report state of car.
earnhardt.fill (50);
earnhardt.drive (200);
earnhardt.fill (10);
System.out.println ("Report for Earnhardt:");
earnhardt.report();
// ---------------------
// Create sports car for Michael Schumacher.
SportsCar schumacher = new SportsCar ("blue", 17.2);
// Fill car with 40 litres of gas, drive 400 kms, and then
// report state of car.
schumacher.fill (40);
schumacher.drive (400);
System.out.println ("\nReport for Schumacher:");
schumacher.report();
}
}
Output
Report for Earnhardt:
Colour: red
Gas: 48 litres
Odometer: 200 km
Fuel Consumption: 15.5 km/litre
Report for Schumacher:
Colour: blue
Gas: 17 litres
Odometer: 400 km
Fuel Consumption: 17.2 km/litre