• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

great exam question, need help

 
sarim raza
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question is from marques third test, i dont know why the answer is 4?, I thought it should be 1, since the variable a, is referencing the underlying object Agg, whose method is getFields
so why is a cast required?
----------------------------------
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());
 
Andrew Edmonds
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,
This is a good example of how assigning a different type to an object can effect expected results. The reason (1) doesn't work is because of Agg is referenced by a BASE type, not an Agg type.
Now, if the Base type had a getFields method then Polymorphism would apply, ie at runtime the Agg method would be called. You can check this out in the Campfire.
Since Base does not contain this method it cannot possibly reference the getFields method in Agg. The only way to call it is to Cast the Base a type to an Agg type first then call it.
Hope this makes sense
Andrew
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic