简体   繁体   English

需要解释Java类的协作/聚合

[英]Need explanation of java Class collaboration/aggregation

I'm working on an assignment where I need to make 3 classes for a car simulator. 我正在做一个作业,需要为汽车模拟器做3个课程。 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)." “里程等级应该能够与FuelGauge对象一起工作。它应该使每行驶24英里时FuelGauge对象的当前燃料量减少1加仑。(汽车的燃油经济性是每加仑24英里)。” 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. 一个很好的解释,将不胜感激。

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. 简单的答案是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);     
     } 
}

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. 如您所见,Mileage类对在构造函数中传递的fuelGague对象具有引用,并且可以通过FuelGague类的公共方法对其进行操作。 I added set method for Mileage class so you can even set different FuelGague class object. 我为Mileage类添加了set方法,因此您甚至可以设置不同的FuelGague类对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM