[英]Adding strings to an Array in Abstract class A, from an extended class B in Java
我正在編寫一個小程序來演示工廠設計模式。 這是一個美食廣場應用程序,可提供不同類型的食物,例如中餐,意大利菜,壽司等。我已經在下面的抽象類中創建了一個數組,並且我試圖通過擴展類添加一個字符串來填充它。
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);
}
}
}
擴展類
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
如果有人可以幫忙看看為什么不添加任何東西,那就太好了。 (如有必要,我可以發布其余課程)。
您的OOP結構很遙遠,並且您似乎濫用了繼承,因為這不是繼承的工作方式或應如何工作。 您的中文課不應擴展FoodCourt,因為它不滿足“是”規則或Liskov替代原則 。 我建議重新設計,以期達到構圖的目的:
getDailySpecial()
方法 restaurantList.get(random.nextInt(restaurantList.size())).getDailySpecial();
問題是這些行:
static String [] dailySpecial = new String[10];
int idx = new Random().nextInt(dailySpecial.length);
String random = (dailySpecial[idx]);
dailySpecial.length為10。在您的描述中,您說您有4個擴展類,您僅使用此數組的4個位置。 但是您正在生成一個從0到9的隨機整數。
因此,如果idx大於3,則您的字符串random可以為null。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.