2016-11-18 52 views
1

我是一个初学者到Java,我奉命执行以下操作:如何将变量指定为参数?

  • 创建一个新类Food
  • 被指定为参数的食物的名称。
  • 食物名称的吸气方法。

我的尝试是这样的:

public class Food 
{ 
    String food;  

    Food() { 
     food = ""; 
    } 
    public String getFood() { 
     return food; 
    } 
} 

我会食品名称被指定为参数更改为:

Food(String food) { 
    food = ""; 
} 

或者任何不同的方式?谢谢。

回答

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; 
    } 
} 
1

是,那么请确保使用参数在体内:

Food(String food) { 
    // need `this` to refer to instance variable food since there's 
    // scope overlap. 
    this.food = food; 
} 
-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); 

     } 

    }