Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Marcus No3-#57

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, that clear my doubt and thank you very much.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic