我有一個受保護屬性高度的子級(擴展)類。 我想訪問它的主程序:子類屬性錯誤
while(line != null)
{
String[] field = line.split("#");
int height = Integer.parseInt(field[0]);
if (field.length ==1)
{
forest[cnt] = new Trees(height);
}
else
{
forest[cnt] = new Shrub(height, field[1]);
}
cnt++;
line = inS.readLine();
}
inS.close();
String s = JOptionPane.showInputDialog("Enter Name to search for");
for(int i = 0; i<forest.length; i++)
{
if (forest[i] instanceof Shrub)
{
String a = forest[i].getName();
System.out.println ("Found");
}
}
}
不過,我得到一個錯誤說,它不能找到方法GetName,但是當我運行笑灌木能正常工作?
謝謝。
嘗試像這樣的類型轉換..'String a =((灌木)forest [i])。getName();'。這是因爲我不認爲父類型中存在'getName()'方法。在這種情況下,你應該明確告訴編譯器。 –