• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Marcus Green Exam 3, Question 57

 
JiaPei Jen
Ranch Hand
Posts: 1309
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2813
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try compiling the code.
Marcus
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic