Skip to main content
ICT
Lesson A4 - Object Behavior
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

LAB ASSIGNMENT A4.1 page 10 of 11

MPG

Background:

  1. Professional programmers carefully design the classes they need before any coding is done. With well-designed classes, programming is much easier and the program has fewer bugs. Object-oriented design consists of deciding what classes are needed, what data they will hold, and how they will behave. All these decisions are documented (written up) and then examined. If something doesn't look right, it is fixed before any programming is done.

  2. The specifications of a class that models the fuel efficiency of a car could be:

Assignment:

  1. Implement a Car class with the following properties.

    1. A Car keeps track of the starting odometer reading, ending odometer reading, and the number of gallons used between readings.

    2. The initial odometer reading is specified in the constructor.

    3. A method calculateMPG calculates and returns the miles per gallon for the car.

    4. A method fillUp simulates filling up the tank at a gas station: odometerReading is the current odometer reading and gallons is the number of gallons that filled the tank. Save these values in instance variables.

    5. With this information, miles per gallon can be calculated. calculateMPG will calculate the miles per gallon since the last time resetMPG was called.

  2. Write a testing class with a main method that constructs a car and calls fillUp and calculateMPG a few times. Sample usage would be

    Car auto = new Car(15);
    System.out.println(“New car odometer reading: ”);
    auto.fillUp(150,8);
    System.out.println(“Miles per gallon” + auto.calculateMPG());
    System.out.println(“Miles per gallon” + auto.calculateMPG());
    auto.resetMPG();
    auto.fillUp(350, 10);
    auto.fillUp(450, 20);
    System.out.println(“Miles per gallon” + auto.calculateMPG());
    auto.resetMPG();
    auto.fillUp(603, 25.5);
    System.out.println(“Miles per gallon” + auto.calculateMPG());

    Sample Output:

    New car odometer reading: 15
    Miles per gallon: 16.875
    Miles per gallon: 16.875
    Miles per gallon: 10.0
    Miles per gallon: 6.0

 

 

Main Previous Next
Contact
 © ICT 2006, All Rights Reserved.