wood burning stoves
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes great exam question, need help 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 "great exam question, need help" Watch "great exam question, need help" New topic

great exam question, need help

sarim raza
Ranch Hand

Joined: Nov 02, 2000
Posts: 232
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();

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

Joined: Nov 05, 2000
Posts: 7
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
I agree. Here's the link: http://aspose.com/file-tools
subject: great exam question, need help
It's not a secret anymore!