aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Marcus No3-#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 No3-#57" Watch "Marcus No3-#57" New topic
Author

Marcus No3-#57

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hi, I am new here. Could anyone explain this why the answer is 4.
Thanks
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 of Base
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());
Baskaran Subramani
Ranch Hand

Joined: Jul 30, 2000
Posts: 38
Hi Alice,

The reason for each choice is as follows.
1) is not correct. Because, object a is of type Base eventhough it refers an object of type Agg. Objects won't forget the type they belong to. so when u call getFields() using a.getFields() it will always check whether the method exists in class a or not. Since it doesn't exist in class a it fails.
2) is not correct. same as previous case.
3) is not correct. It has no effect as it is trying to cast the object with the same type it belongs to. so it is same as calling [a]a.getFields()[/b].
4) is correct. Because, a is cast to the type Agg using (Agg) a).(Down Casting) This is correct, Because a is refering to the object of the same class(Agg). calling getFields() using ((Agg) a).getFields()) correctly calls the method in Agg .
hope this clears ur doubt.
Thanks,
Baskaran.

[This message has been edited by Baskaran Subramani (edited September 05, 2000).]
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hi, that clear my doubt and thank you very much.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Marcus No3-#57