user7128699 user7128699 - 16 days ago 7
Java Question

How to specify a variable a an argument?

I'm a beginner to Java, I have been instructed to carry out the following:


  • Create a new class
    Food

  • The name of the food specified as an argument.

  • A getter method for the name of the food.



My attempt looks like:

public class Food
{
String food;

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


Would I the name of food be specified as an argument be changed to:

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


Or any different way? Thanks.

Answer

Yes, and you have to assign the argument to a field where you store the name of the food. This is the code with the explanation in comments.

//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;
    }
}
Comments