Hi,
It is from Meacus Green's exam 3.
class Base {}
class Agg extends Base{
public
String getFields(){
String name = "Agg";
return name;
}
}
public class Avf{
public static void main(String argv[]){
Base a = new Agg();
}
}
What code placed after the comment //Here will result in calling the getFields method of Base resulting in the output of the string "Agg"?
1) System.out.println(a.getFields());
2) System.out.println(a.name);
3) System.out.println((Base) a.getFields());
4) System.out.println( ((Agg) a).getFields());
The answer is
4) System.out.println( ((Agg) a).getFields());
The Base type reference to the instance of the class Agg needs to be cast from Base to Agg to get access to its methods.The method invoked depends on the object itself, not on the declared type. So, a.getField() invokes getField() in the Base class, which displays Base. But the call to ((Agg)a).getField() will invoke the getField() in the Agg class. You will be unlucky to get a question as complex as this on the exam.
--------------------
I WOULD LIKE TO KNOW, HOW COME THE ANSWER IS 4 .THE METHOD CALL DEPENDS ON THE OBJECT.SO IN NO CASE WE WILL GET TO CALL THE getFields() METHOD OF THE Base CLASS.
SO ANSWER COULD BE 3.BY CASTING TO Base CLASS.
PLEASE EXPLAIN ME WHEN DOES THE Base CLASS METHOD GETS INVOKED.(OTHER THAN MAKING THE METHOD STATIC)
THANKS IN ADVANCE
Mita