X985: Object Oriented Design 3

For this question, you will be working within the Person class. We will be using the Person and Car classes from the previous question again, but adding in a third class called Wallet.

public class Person
{
    public Car car;
    public Wallet wallet;

    public Person(Car c)
    {
        this.car = c;
        // person will always start with $100 USD
        this.wallet = new Wallet(100.00);
    }
}

public class Car
{
    // miles the car can go with a full tank
    private int totalMiles;

    // miles left before we need to get gas
    private int milesUntilGas;

    // when a car is created it has a full tank of gas
    public Car(int miles)
    {
        this.totalMiles = miles;
        this.milesUntilGas = miles;
    }

    /**
     * Drives the car the specified number of miles.
     * We can't drive more miles than we have gas for.
     *
     * @param miles, int number of miles to drive
     * @return true if car successfully drives, otherwise false
     */
    public boolean drive(int miles)
    {
        if (miles <= this.milesUntilGas)
        {
            this.milesUntilGas = this.milesUntilGas - miles;
            return true;
        }
        return false;
    }

    /**
     * Represents filling up the gas tank of the car.
     */
    public void fillUpGasTank()
    {
        this.milesUntilGas = totalMiles;
    }
}

public class Wallet
{
    private double cashOnHand;

    public Wallet(double cash)
    {
        this.cashOnHand = cash;
    }

    public boolean canAfford(double price)
    {
        return price <= this.cashOnHand;
    }

    public void purchase(double price)
    {
        this.cashOnHand = this.cashOnHand - price;
    }

    public double getCashOnHand()
    {
        return cashOnHand;
    }
}

This time, you will be completing a method within the Person class called getGas() that takes in a double representing the total price of gas. Finish the method such that if the person can afford to get gas, they do so and return the value true. Otherwise do not get gas and return false.

Your Answer:

Feedback

Your feedback will appear here when you check your answer.