0

我正在做一项任务,我需要为汽车模拟器制作 3 节课。一个用于燃料,一个用于里程。“里程等级应该能够与 FuelGauge 对象一起使用。每行驶 24 英里,它应该将 FuelGauge 对象的当前燃料量减少 1 加仑。(汽车的燃油经济性为每加仑 24 英里)。” 我只是在努力理解如何正确地将这些类链接在一起,以便他们可以做必要的事情。

非常感谢某人的良好解释。

4

1 回答 1

0

我希望我能正确理解你的问题。简单的答案是 FuelGauge 类将具有属性 amount,可以通过简单的 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);     
     } 
}

如您所见,Mileage 类引用了在构造函数中传递的fuelGague 对象,并且可以通过FuelGague 类的公共方法对其进行操作。我为 Mileage 类添加了 set 方法,因此您甚至可以设置不同的 FuelGague 类对象。

于 2012-04-18T19:21:38.097 回答