简体   繁体   中英

How to use private class variable using interface implemented in a different class

Food is a standalone class, doesn't inherits from anything.


public class Food {
    private String name;

    public Food() {}
                
    public Food(String Name) {
        this.name = Name;
    }
                
    public String getName() {
        return this.name;
    }
                
    public void setName(String name) {
        this.name = name;
    } }

Below is the interface:

 public interface Eater{ public void eat(Food food); }

How can i use the interface in Person class (see below) to access private variable name from Food class?

Here is what I am trying to do by creating an object explicitly :

public class Person implements Eater {
    public String foodName;
        
    public void eat(Food food) {
        Food testFood = new Food();
        this.foodName = testFood.getName();
    }
}

But how can i do something like that without creating an object explicitly ? Because I want this method to work for every instanced of Food .

Just call getName on the food parameter.

public class Person implements Eater {
    public String foodName;
        
    public void eat(Food food) {
        this.foodName = food.getName();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM