java - 从 Java 中的扩展类 B 将字符串添加到抽象类 A 中的数组

标签 java arrays class abstract

我正在编写一个小程序来演示工厂设计模式。这是一个美食广场应用程序,提供不同类型的食物,如中国、意大利、寿司等。我在下面的抽象类中创建了一个数组,并尝试通过扩展类添加字符串来填充它。

abstract public class FoodCourt
{
    String name;            //e.g. italian, chinese etc...
    static String [] dailySpecial = new String[10];
    int idx = new Random().nextInt(dailySpecial.length);
    String random = (dailySpecial[idx]);

    public String getName()
    {
        return name;
    }

    public void takeOrder()
    {       
        System.out.println("You ordered " + random + " from our list of Daily Specials");
    }

    public void serve()
    {
        System.out.println(" -> Serving " + random + " from our " + name + " menu"); //Serving Chow Mein from our Chinese menu
    }

    public void printList()
    {
        for (String name : dailySpecial) 
        {
            System.out.println(name);
        }   
    }
}

扩展类(class)

public class Chinese extends FoodCourt
{
    public Chinese()
    {
        name = "Chinese";
        String s = "Chicken Chow Mein";
        dailySpecial[0] = s;
    }
}

每个扩展类(有 4 个)都会向数组添加一个特殊的菜肴,但它会输出到屏幕,如下所示:

You ordered null from our list of Daily Specials
-> Serving null from our Chinese menu
Chinese food served

什么时候应该是这样的

You ordered Chicken Chow Mein from our list of Daily Specials
-> Serving Chicken Chow Mein from our Chinese menu
Chinese food served

如果有人可以帮忙并了解为什么没有添加任何内容,那就太好了。 (如果有必要,我可以发布其余的类(class))。

最佳答案

你的 OOP 结构已经很糟糕了,你看起来滥用了继承,因为这不是继承的工作方式或应该工作的方式。你的中文类不应该扩展 FoodCourt,因为它不满足“is-a”规则或 Liskov substitution principle 。我建议从组合角度进行重新设计:

  • FoodCourt 应该保存一个扩展 Restaurant 的对象列表,称为restaurantList。从一开始就做对。
  • 您可以为 Restaurant 提供每个子类都扩展的 getDailySpecial() 方法
  • FoodCourt 将在迭代列表时调用此方法。
  • 您将使 Restaurant 变得抽象,而您的工厂将创建具体的 Restaurant 实例。
  • 在实现事物时,父类不应该有固定的数组。
  • 要获取随机每日特价,只需从列表中随机获取一家餐厅并调用其获取每日特价方法:restaurantList.get(random.nextInt(restaurantList.size())).getDailySpecial();

关于java - 从 Java 中的扩展类 B 将字符串添加到抽象类 A 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20908708/

相关文章:

python - 如何使用数组中的方法将date_range 转换为字符串?

c++ - 使用枚举

Typescript - 将类类型存储为变量,以便从中创建对象或其他等效功能

java - 如何阻止 findbugs-maven-plugin 验证 querydsl 生成的类

java - 在 JLabel 中逐字母显示字符串 "animation"?

java - Eclipse:未调用 javax.annotation PostConstruct

java - 我正在使用 Microsoft SQL Server 2014 和 NetBeans 8.0.2 - getConnection 始终带有下划线红色

python - Numpy 始终将邻居获取为 3x3 矩阵

java - 将两个数组复制到一个数组

python - 散列 Python 类是个好主意吗?