• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

call to shadowed static method at runtime!!!

 
Ranch Hand
Posts: 321
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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();
}
}
 
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic