[英]Java - project, adding an object to class
我目前正在努力為我的項目解決這個問題。 我目前有一個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);
}
}
入門子類與主子類和甜點子類相同
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
}
到目前為止,我:添加食物(包括名稱,價格,描述,卡路里),列出所有食物,添加課程以搜索課程(按課程編號或名稱),列出所有課程,我只需要這樣做,但是我在努力感謝在課程上附加食物
如果您嘗試向課程中添加食物,則應使用“具有”關系,例如:
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來擴展課程,因為extends是for和“ 是 ”關系,所以我將其稱為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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.