Question

I'm working on an assignment where I need to make 3 classes for a car simulator. One for the fuel and one for the mileage. "The mileage class should be able to work with a FuelGauge object. It should decrease the FuelGauge object's current amount of fuel by 1 gallon for every 24 miles traveled. (The car's fuel economy is 24 miles per gallon)." I'm just really struggling on understanding how to properly link the classes together so that they can do what is necessary.

A good explanation from someone would be greatly appreciated.

Was it helpful?

Solution

I hope I understand your problem correctly. Simple answer is that FuelGauge class will have attribute amount, which will be accessible through simple setter/getter.

public class FuelGague {

    private double amount;
    // Starting amount of fuel
    public FuelGague(double amount) {
        this.amount = amount;

    }
    // Not sure if you really need this method for your solution. This is classic setter method.
    public void setAmount(double amount) {
        this.amount = amount;
    }

    public double getAmount() {
        return amount;
    }
    // I guess this is what do you actually want to do 
    public void changeAmount(double difference) {
        amount += difference;
    }

}


public class Mileage  {

       private FuelGague fuelGague;

       public Mileage(FuelGague fuelGague) {
           this.fuelGague = fuelGague;
       }
       // This will be main method where you can decrease amount for guelGague
       public void methodForMileage() {
        fuelGague.changeAmount(-1);
       }

        public FuelGague getFuelGague() {
        return fuelGague;
    }

    public void setFuelGague(FuelGague fuelGague) {
        this.fuelGague = fuelGague;
    }

     public static void main(String[] args) 
     { 
            FuelGague fuelGague= new FuelGague(50); 
            Mileage mil = new Mileage(fuelGague);     
     } 
}

As you can see Mileage class has refference to fuelGague object which is passed in constructor and it can be manipulated by public method of FuelGague class. I added set method for Mileage class so you can even set different FuelGague class object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top