我有一个受保护属性高度的子级(扩展)类。 我想访问它的主程序:子类属性错误
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()'方法。在这种情况下,你应该明确告诉编译器。 –