简体   繁体   中英

How to do object.getClass().getName() in Java

I want to implement to classes, Food and FoodFactory such that they satisfies the following input and output.

//Input:
FoodFactory ff = new FoodFactory();
Food f1 = ff.getFood('Fruit');
Food f2 = ff.getFood('Meat');
f1.serveFood(); 
f2.serveFood();
System.out.println(f1.getClass().getSuperClass().getName());
System.out.println(f1.getClass().getName());
System.out.println(f2.getClass().getName());

//Output:
I'm serving Fruit
I'm serving Meat
Food
Fruit
Meat

Suppose we have the following constraints:

  1. Only write the two classes Food and FoodFactory
  2. Only java.util.* is allowed

What I don't know is how to make getClass().getName() working in different situation. I can only get FoodFactory .

Thanks!

Looks like you are practicing some OO with Java . It's better if you ask a doubt instead the full scenario.

However I will paste a sample here and you can ask any doubt you have. FoodFactory class below, note that for a name you will get the right Object.

public class FoodFactory {

  public Food getFood(String food) {

    if ("Meat".equals(food)) {
      return new Meat();
    } else if ("Fruit".equals(food)) {
      return new Fruit();
    }
    throw new IllegalArgumentException("No food found with name " + food);
  }
}

Both your Food classes should be created, in this case Meat and Fruit.

public class Meat extends Food {
}

Your Food will print message based on current classes. Others will inherit the behavior.

public class Food {
  public void serveFood() {
    System.out.println("I'm serving " + getClass().getSimpleName());
  }
}

Then you can simply run your scenario and note that getClass will run for right hierarchy.

FoodFactory ff = new FoodFactory();
Food f1 = ff.getFood("Fruit");
Food f2 = ff.getFood("Meat");
f1.serveFood();
f2.serveFood();
System.out.println(f1.getClass().getSuperclass().getSimpleName());
System.out.println(f1.getClass().getSimpleName());
System.out.println(f2.getClass().getSimpleName());

Try to play with it and understand.

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