• 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
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

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
 
Arthur, where are your pants? Check under this tiny ad.
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic