我是Java的初学者,我已被指示执行以下操作:
Food
我的尝试看起来像:
public class Food
{
String food;
Food() {
food = "";
}
public String getFood() {
return food;
}
}
我是否将食物名称指定为参数改为:
Food(String food) {
food = "";
}
还是以任何不同的方式?感谢。
答案 0 :(得分:1)
是的,然后确保使用正文中的参数:
ID EXPIRATION_DATE
----------- -----------------------
1 1997-12-31 00:00:00.000
77 2001-12-31 00:00:00.000
答案 1 :(得分:0)
是的,您必须将参数分配给存储食物名称的字段。这是代码中带有解释的代码。
//class Food
public class Food {
//field that stores the name of the food
private String name;
//constructor that takes the name of the food as an argument
public Food(String name){
this.name = name;
}
//getter
public String getName() {
return name;
}
}
答案 2 :(得分:-1)
public class Food {
String food;
Food()
{
}
public String getFood()
{
return food;
}
public void setFood(String food)
{
//this is used as to set the value that you passed from your main class throught your object
this.food = food;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Food object=new Food();
object.setFood("Apple");
String name= object.getFood();
System.out.print(name);
}
}