以下代码:
class Base{}
class Agg extends Base{
public String getFields(){
String name="Agg";
return name;
}
}
public class Avf{
public static void main(String args[]){
Base a=new Agg();
//please take a look here
System.out.println(((Agg)a).getFields()); // why a needs cast to Agg?
}
}
我的问题是:为什么我们不能替换 ((Agg)a).getFields()
为a.getFields()
?为什么我们需要 type cast on a
?我提到它getFields()
没有在 class 中定义Base
,因此 classAgg
没有从它的基类扩展这个方法。但是,如果我 getFields()
在 class中定义了方法Base
,例如:
class Base{
public String getFields(){
String name="This is from base getFields()";
return name;
}
}
一切都会好起来的。那么 ((Agg)a).getFields() 等价于 a.getFields()
在代码中
Base a=new Agg();
这条线是否意味着a
有引用Agg()
并且可以直接调用class的方法Agg
。但是,如果我不在getFields()
类中定义方法,为什么会有区别Base
?谁能给我解释一下?