The following code:
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?
}
}
My question is: why we can’t replace ((Agg)a).getFields() to a.getFields()? Why we need to type cast on a? And I mention that getFields() is not defined in class Base, thus class Agg does not extend this method from its base class. But if I defined method getFields() in class Base,
like:
class Base{
public String getFields(){
String name="This is from base getFields()";
return name;
}
}
everything would be all right. Then
((Agg)a).getFields() is equivalent to a.getFields()
In the code
Base a=new Agg();
Does this line means a has the reference of Agg() and a can invoke directly the method of class Agg. But why is there difference if I do not define the method getFields() in class Base? Can any one explain this to me?
Because
Basedoesn’t have a method calledgetFields.The declaration
…tells the compiler the interface you’re going to use when using
a. It doesn’t matter that you then assignnew Agg();to it, the interface you have toais stillBase. And sinceBasedoesn’t havegetFields, trying to usegetFieldsis a compilation error.It means
acontains a reference to anAggobject, but the interface to that object is defined byBase, notAgg, and so you can’t callAggmethods on it if they’re not defined byBase(without a cast, and casts are dangerous and should be avoided where possible).If your code needs access to methods or fields defined by
Agg, then the variable (or argument, in my example) should be declaredAgg a, notBase a.This is a fundamental thing about OOP in general and the OOP implementation in Java in particular: There’s a big difference between the interface to an object and the implementation of the object. In your example, you know
Base ais really anAgg, but consider this:Clearly here the compiler shouldn’t allow you to use methods or fields on
athat aren’t defined byBase. It’s the same situation in your code, just less obvious.