File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

call to shadowed static method at runtime!!!

 
Rishi Singh
Ranch Hand
Posts: 321
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The output to the following programme is "Child.Test()" followed by Base.Test();. How come the call to the method baseObject.test() takes up the Base class test()method.Is it that it is static and the call to it is resolved at class loading time, though the baseO bject is of class Child???.please clarify
class Base
{
static void test() {
System.out.println("Base.test()");
}
}
////////////////////////////////////////////
public class Child extends Base {
static void test() {
System.out.println("Child.test()");
}
static public void main(String[] a) {
Child anObj = new Child();
anObj.test();
Base baseObj = (Base)anObj;
baseObj.test();
}
}
 
Rajiv Ranjan
Ranch Hand
Posts: 61
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rishi:
This is a special case applicable to staic methods.
Just remember a simple rule :
" The choice of the static method depends on the class of the reference variable that calls it"
Rajiv
 
Sivaram Ghorakavi
Ranch Hand
Posts: 56
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Static members belock to the class not to the instance. So in this case, static method overriding, when anObj.test() is called it refers to the method from the class reference that is Child. Saying that
Base baseObj = (Base)anObj;
baseObj.test(); would referer to the test()from class Base.
Hope this helps.
BOL
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic