构造 Collection<Interface> 在 Java 中如何工作?

问题描述 投票:0回答:1

我遇到了一个问题。有一个类和一个接口:

班级:

public class Food implements NutritionalElement {
private String name;
private double calories;
private double proteins;
private double carbs;
private double fat;
private HashMap<String, ArrayList<Double>> rawMaterialsList = new HashMap<String, ArrayList<Double>>();

public void defineRawMaterial(String name,
                                  double calories,
                                  double proteins,
                                  double carbs,
                                  double fat){
    this.name = name;
    this.calories = calories;
    this.proteins = proteins;
    this.carbs = carbs;
    this.fat = fat;
    ArrayList<Double> nutrision = new ArrayList<>();
    nutrision.add(this.calories);
    nutrision.add(this.proteins);
    nutrision.add(this.carbs);
    nutrision.add(this.fat);
    rawMaterialsList.put(this.name, nutrision);
}

/**
 * Retrieves the collection of all defined raw materials
 * @return collection of raw materials through the {@link NutritionalElement} interface 
 * problem is here      
 */
public Collection<NutritionalElement> rawMaterials(){

    
    return res;
}

还有一个界面:

package diet;



public interface NutritionalElement {
public String getName();

public double getCalories();


public double getProteins();


public double getCarbs();


public double getFat();


public boolean per100g();

}

我完全迷失了,我从来没有遇到过这样的事情。我会要求帮助我理解如何在课堂上完成该方法。谢谢你

java class interface
1个回答
0
投票

根据常识,你的结构是不正确的。营养元素是碳水化合物、脂肪、蛋白质,可能还有其他我不知道的东西。看来你应该有代表每个元素的类。

class Carbohydrates implements NutritionalElement {
  //implement the methods
}

为其他元素创建类似的类。

那么

Food
应该看起来像:

class Food {

  private List<NutritionalElement> elements;
  
  //constructors

  //other methods, if necesarry

  public Collection<NutritionalElement> rawMaterials(){  
    return this.elements;
  }
}

食物不是一个

NutritionalElement
,但它有很多
NutritionalElement

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.