aspose file tools*
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


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Marcus Green Exam 3, Question 57" Watch "Marcus Green Exam 3, Question 57" New topic
Author

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();
//Here
}
}
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 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
Rancher

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


SCWCD: Online Course, 50,000+ words and 200+ questions
http://www.examulator.com/moodle/course/view.php?id=5&topic=all
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Marcus Green Exam 3, Question 57