[英]Java - project, adding an object to class
I am currently struggling to figure out this problem for my project. 我目前正在努力为我的项目解决这个问题。 I currently have a Food class that stores name, price and description with getters and setters and a toString. 我目前有一个Food类,该类存储名称,价格和描述以及getter,setter和toString。 And a course class with subclasses (starter, main dessert). 还有一个带有子类的课程(入门级,主要甜点)。 I am trying to figure out how to attach a Food to a Course. 我试图弄清楚如何在课程中添加食物。
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);
}
}
starter subclass its the same with main and dessert subclasses 入门子类与主子类和甜点子类相同
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
}
so far ive: adding food (with a name, price, description, calories) listing all food items adding courses searching for a course (by course number or name) listing all courses I only need to do this but I'm struggling any help is appreciated attaching food to courses 到目前为止,我:添加食物(包括名称,价格,描述,卡路里),列出所有食物,添加课程以搜索课程(按课程编号或名称),列出所有课程,我只需要这样做,但是我在努力感谢在课程上附加食物
If your trying to add a Food to a Course, you should use a "has a" relationship for example: 如果您尝试向课程中添加食物,则应使用“具有”关系,例如:
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;
}
}
I also wouldn't use StarterFood to extend a Course, because extends is for and " is a " relationship, I would call it StarterCourse and then add a default food for that course in the constructor. 我也不会使用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);
}
}
Then in your main class to test it out try this: 然后在您的主类中进行测试:
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.