• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Marcus q# 57

 
Ketuman Joshi
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys,
Can anyone explain me why answer is 4 & not 1& 4.
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());
Thanks
Ketuman Joshi
 
quan zhu
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
object a isA type Base, which does not have a method called "getFields".
Since a is really a "Egg" object, we can cast it.
 
Ken Pullin
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1 is not correct because the base class doesn't have a getFields() method.
 
Alamu Vinai
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Base class does not have getFields() method.
The compiler just looks for the base class variable and the base class methods, in this case we don't have getFields() method in base class and hence compiler error.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic