This is actually one of the high-quality questions I can find in the free mocks:
What code placed after the comment //Here will result in calling the getFields method 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 right answer is No4, But the explanation is completely irrelevant:
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 think Marcus just didn't update the explanation with new devised question.
I first chose No1, which actually will cause compiler error. Even though a actually refer to type Agg, but the compiler doesn't know that. It only knows a is Base reference. Since there is no getField() method in Base class. It sent an error message. This question is a little tricky, but really tests the concept of inheritance thoroughly.