我正在努力为我的项目找出这个问题。我目前有一个Food类,用getter和setter以及toString存储名称,价格和描述。还有一个带有子类的课程(入门,主要甜点)。我想弄清楚如何将食物附加到课程中。
public abstract class Course{
//fields
//protected only accessible to subclasses
protected MenuList starter;
protected MenuList main;
protected MenuList dessert;
protected MenuList drinks;
//Constructor
public Course(){
starter = new MenuList();
main = new MenuList();
dessert = new MenuList();
drinks = new MenuList();
}
//getters and setters
//methods
public abstract MenuList getList();
//add item
public void addItem(String course, String foodName, double price, String description, int calories){
this.addItem(course, foodName, price, description, calories);
}
}
启动子类与main和dessert子类相同
public class StarterFood extends Course{
//fields
//constructor
public StarterFood(){
//course,
starter.addItem("starter", "chicken wings", 2.30, "very nice", 150, false);
}
@Override
public MenuList getList() {
return starter;
}
//Constructors
//getters and setters
//methods
}
到目前为止: 添加食物(名称,价格,描述,卡路里) 列出所有食品 添加课程 搜索课程(按课程编号或名称) 列出所有课程 我只需要做到这一点,但我很挣扎,任何帮助都会受到赞赏 将食物附加到课程
答案 0 :(得分:1)
如果您尝试将食物添加到课程中,则应使用“有”关系,例如:
public class Course {
private Food food;
public Course(Food food) {
this.food = food;
}
public Course() {
}
public Food getFood() {
return this.food;
}
public void setFood(Food food) {
this.food = food;
}
}
我也不会使用StarterFood扩展课程,因为扩展用于和“是”关系,我称之为StarterCourse然后添加默认值在构造函数中用于该课程的食物。
public class StarterCourse extends Course {
public StarterCourse(Food food) {
// here call the super classes constructor
// add items via the Course constructor
super(food);
}
}
然后在你的主要课程中测试它,试试这个:
public class Main() {
public static void main() {
// First create new Food object
Food food = new Food();
// Create a new StarterCourse and add the Food object to it
StarterCourse starterCourse = new StarterCourse(food);
}
}