File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Marcus No3-#57" Watch "Marcus No3-#57" New topic

Marcus No3-#57

Ranch Hand

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

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

Joined: Nov 22, 2008
Posts: 18944
Hi, that clear my doubt and thank you very much.
I agree. Here's the link:
subject: Marcus No3-#57
It's not a secret anymore!