[英]How to do object.getClass().getName() in Java
我想实现类, Food
和FoodFactory
,以便它们满足以下输入和输出。
//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
假设我们有以下约束:
Food
和FoodFactory
两个类 我不知道如何让getClass().getName()
在不同的情况下工作。 我只能得到FoodFactory
。
谢谢!
看起来您正在使用 Java 练习一些 OO。 如果你问一个疑问而不是完整的场景会更好。
但是,我将在此处粘贴一个示例,您可以提出任何疑问。 下面的 FoodFactory 类,请注意,对于名称,您将获得正确的 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);
}
}
应该创建两个 Food 类,在本例中为 Meat 和 Fruit。
public class Meat extends Food {
}
您的食物将根据当前课程打印消息。 其他人将继承该行为。
public class Food {
public void serveFood() {
System.out.println("I'm serving " + getClass().getSimpleName());
}
}
然后您可以简单地运行您的场景并注意 getClass 将针对正确的层次结构运行。
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());
试着玩弄它并理解它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.