user7128699 user7128699 - 1 year ago 68
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

  • 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 Source

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){ = name;

    public String getName() {
        return name;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download