需要解释java类协作/聚合

时间:2012-04-18 18:43:04

标签: java class collaboration aggregation

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

非常感谢某人的好解释。

1 个答案:

答案 0 :(得分:0)

我希望我能正确理解你的问题。 简单的答案是FuelGauge类将具有属性数量,可通过简单的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类的公共方法进行操作。我为前程万里课程添加了set方法,这样你甚至可以设置不同的FuelGague类对象。