0
所以我有一個抽象的父類和6個子類擴展它。我有一個從文件中讀取數據的fileRead(String)方法。該文件的第一行有一個類別ID(FOODTYPE _CATID)和一個名稱,用'|'分隔(管道)字符,這是我在String Tokenizer中使用的分隔符。我有6個if語句檢查令牌並初始化適當的對象。但是,這是我碰到的問題,我想在方法以後使用的對象,但不能因爲從令牌確定一個子對象並初始化它
- A),因爲它是在if()語句編譯器認爲威力 沒有已經初始化並且
- B)我不能在if語句之前初始化它,因爲它是 的抽象。我也只想使用這個單一的對象,我不想 初始化6個不同的對象,並有50個不同的if語句 在一個單一的方法。
所以我的問題是,我該如何只爲這類問題使用一個對象?下面是一些供參考代碼:
Public abstract class Recipe { methods }
Public class Soup extends Recipe { methods } //There are 5 other classes like this
Public class Controller
{
doSomething() { logic }
doThis() { logic };
readFile(String str)
{
recipeFile.open("recipes.dat");
if (recipeFile.exists())
{
// read first line from the recipe file
recipeLine = recipeFile.readLine();
String Tokenizer token;
while (recipeLine != null)
{
token = new String Tokenizer(recipeLine, "|");
Recipe recipe;
if(token.hasMoreTokens())
{
if(token.equals(SOUP_CATID))
{
recipe = new Soup();
recipe.setName(token.toString());
}
...more if statements checking other catId's
}
Ingredients i = new Ingredient();
recipeFile.open("ingredients.dat");
while(logic)
{
//This will not work because recipe
//still hasn't been initialized before the if
//statements
recipe.addIngredient(i);
}
}
}
}
}
編輯解決 - 所有我需要做的就是初始化配方空的if語句之前。 食譜recipe = null; 沒有產生任何錯誤和代碼/邏輯的作品。
我其實只是想通了。這並不是說我不知道配方會被初始化,編譯器不斷抱怨配方可能沒有被初始化。無論如何,我所要做的就是在if語句之前將配方初始化爲null。沒有產生任何錯誤。感謝您的意見 – persinac