File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Marcus Green Exam 3, Question 57 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Marcus Green Exam 3, Question 57" Watch "Marcus Green Exam 3, Question 57" New topic

Marcus Green Exam 3, Question 57

JiaPei Jen
Ranch Hand

Joined: Nov 19, 2000
Posts: 1309
Given 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 argv[]){
Base a = new Agg();
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(;
3) System.out.println((Base) a.getFields());
4) System.out.println( ((Agg) a).getFields());
The answer is 4. However, I think the answer is 1 because the type of the object is Agg (although its reference type is Base), and when a method such as getFields(); is called, the method in the Agg class is executed. Do we "have to" cast "a" like in Answer 4? Please point out my mistake if there is any.
Sam Wong
Ranch Hand

Joined: Dec 07, 2000
Posts: 133
a is of type Base. Therefore, it has no knowledge of the method getFields(). This will fail compilation. Hence, 4 is the correct answer. 1 will not work. Try it out and see for yourself.
Now, if Base also defined a method getFields with the same signature, then 1 will also work and print "Agg".
Marcus Green
arch rival

Joined: Sep 14, 1999
Posts: 2813
Try compiling the code.

SCWCD: Online Course, 50,000+ words and 200+ questions
I agree. Here's the link:
subject: Marcus Green Exam 3, Question 57
It's not a secret anymore!