aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes overriding methods, please help 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 "overriding methods, please help" Watch "overriding methods, please help" New topic
Author

overriding methods, please help

mita
Ranch Hand

Joined: Jul 19, 2000
Posts: 50
Hi,
It is from Meacus Green's exam 3.
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());

The answer is
4) System.out.println( ((Agg) a).getFields());
The Base type reference to the instance of the class Agg needs to be cast from Base to Agg to get access to its methods.The method invoked depends on the object itself, not on the declared type. So, a.getField() invokes getField() in the Base class, which displays Base. But the call to ((Agg)a).getField() will invoke the getField() in the Agg class. You will be unlucky to get a question as complex as this on the exam.
--------------------
I WOULD LIKE TO KNOW, HOW COME THE ANSWER IS 4 .THE METHOD CALL DEPENDS ON THE OBJECT.SO IN NO CASE WE WILL GET TO CALL THE getFields() METHOD OF THE Base CLASS.
SO ANSWER COULD BE 3.BY CASTING TO Base CLASS.
PLEASE EXPLAIN ME WHEN DOES THE Base CLASS METHOD GETS INVOKED.(OTHER THAN MAKING THE METHOD STATIC)
THANKS IN ADVANCE
Mita
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hi,
q. 1 to 3 you can get compile errors. During compilling, a is a reference of the class Base. the reference is looking for the method getField() in the class of Base, not its subclass.
However, if you cast the a reference to the type of the class Agg, it would not give you compile error in that Base a reference
is casted back to the type of the class Agg in which the method
getField() is defined. Hope the explanation help you little bit.
mita
Ranch Hand

Joined: Jul 19, 2000
Posts: 50
Thanks for the explanation, but I could compile option 3 & it compiles fine & calls the getField() method of the subclass.I understand the concept but a little confused here.
Thanks
mita
Chris Cleverley
Greenhorn

Joined: Mar 09, 2007
Posts: 22
Where is the comment //Here in the code ??
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: overriding methods, please help